Latest Tutorials| Questions and Answers|Ask Questions?|Site Map




Have Programming Question? Ask it here!
 
 
 


SUJATHA NAIDU
javqa
2 Answer(s)      4 years and 11 months ago
Posted in : Java Beginners



Advertisement
View Answers

September 15, 2009 at 6:03 PM


package saigun.pacificCorp.util;

import java.util.ArrayList;
import java.util.List;

public class UniqueElement {

public static void main(String[] args) {

List firstList = new ArrayList();
firstList.add(new Integer(3));
firstList.add(new Integer(5));
firstList.add(new Integer(8));
firstList.add(new Integer(1));

List secondList = new ArrayList();
secondList.add(new Integer(2));
secondList.add(new Integer(5));
secondList.add(new Integer(8));
secondList.add(new Integer(9));
List different = new ArrayList();
for(int i=0; i < firstList.size(); i++){
if(!secondList.contains(firstList.get(i)))
different.add(firstList.get(i));
}
for(int i=0; i < firstList.size(); i++){
if(!firstList.contains(secondList.get(i)))
different.add(secondList.get(i));
}
System.out.println("List of different Element = "+different);
}
}


September 16, 2009 at 3:04 PM


Hi Friend,

Try the following code:

import java.util.*;

public class DisplayDifferentElement{
public static void main(String[]args){
ArrayList a1 = new ArrayList();
ArrayList a2 = new ArrayList();
a1.add("a");
a1.add("fdf");
a1.add("h");
a1.add("d");
a1.add("e");

a2.add("a");
a2.add("b");
a2.add("ch");
int array1Size = a1.size();
int array2Size = a2.size();

Set s = new HashSet();
s.addAll(a1);
s.addAll(a2);

ArrayList list = new ArrayList();

for(int i=0; i<a2.size(); i++) {
if(!a1.contains(a2.get(i))) {
list.add(a2.get(i));
}
}
for(int i=0; i<a1.size(); i++) {
if(!a2.contains(a1.get(i))) {
list.add(a1.get(i));
}
}
System.out.println("Elements which are different: "+list);
System.out.println("");
for(int i = 0; i < list.size(); i++){
System.out.print((String)list.get(i)+" ");
}
}
}

Thanks


Related Tutorials/Questions & Answers:
 

 

 

DMCA.com