2011-08-24 20 views
5

Mam dwa Arraylists:Porównaj dwa ArrayList

ArrayList a1 = new ArrayList(); 
a1.add("5"); 
a1.add("10"); 
a1.add("20"); 
a1.add("50"); 
a1.add("100"); 
a1.add("500"); 
a1.add("1000"); 

ArrayList a2 = new ArrayList(); 
a2.add("50"); 
a2.add("500"); 
a2.add("1000"); 

Jak mogę porównać to dwa arraylists i dodać do new ArrayList (a3) ​​z 1, jeżeli a2 istnieje w A1 i 0 jeśli nie istnieje, więc wynik będzie poniżej dla tablicy tablic a3?

a3[0] = 0 
a3[1] = 0 
a3[2] = 0 
a3[3] = 1 
a3[4] = 0 
a3[5] = 1 
a3[6] = 1 

góry dzięki

Odpowiedz

11

pierwsze, radziłbym ci use generics. A po drugie, dla a2 może być zamiast tego Set. Po trzecie, możesz chcieć zmienić wersję z String na Integer (ponieważ wszystkie są liczbami całkowitymi).

Ale dla przykładu jest to sposób, aby to zrobić:

ArrayList<Integer> a3 = new ArrayList<Integer>();    
for (String a : a1) 
    a3.add(a2.contains(a) ? 1 : 0); 

Pełny przykład (z typem HashSet i Integer):

public static void main(String... args) { 
    List<Integer> a1 = Arrays.asList(5, 10, 20, 50, 100, 500, 1000); 
    Set<Integer> a2 = new HashSet<Integer>(Arrays.asList(50, 500, 1000)); 

    ArrayList<Integer> a3 = new ArrayList<Integer>();     

    for (Integer a : a1) 
     a3.add(a2.contains(a) ? 1 : 0); 

    System.out.println(a3); 
} 

wyjściowa:

[0, 0, 0, 1, 0, 1, 1] 
0

Psuedo cod e

Check both a1 and a2 for length. say a1 is longest 
a3 = new arraylist(a1.length) 
for(i=0 to a2.length) 
if(a1.contains(a2.get(i)) 
    a3.get(i)++; 
0

coś takiego:

ArrayList<Integer> a3 = new ArrayList<Integer>(); 

for (String v : a1) { 
    if (a2.contains(v)) { 
     a3.add(1); 
    } else { 
     a3.add(0); 
    } 
} 
1

to to zrobi.

Zauważ, że twoje pytanie określa int[] jako typ wyjściowy, co nie jest tym, co bym wybrał - Lista byłaby prawdopodobnie lepsza, jednak ta odpowiedź spełnia to, o co prosiłeś, w przeciwieństwie do każdej innej odpowiedzi, jaką widziałem do tej pory.

public static void main(String[] args) { 
    ArrayList<String> a1 = new ArrayList<String>(); 
    a1.add("5"); 
    a1.add("10"); 
    a1.add("20"); 
    a1.add("50"); 
    a1.add("100"); 
    a1.add("500"); 
    a1.add("1000"); 

    ArrayList<String> a2 = new ArrayList<String>(); 
    a2.add("50"); 
    a2.add("500"); 
    a2.add("1000"); 

    int[] matches = new int[a1.size()]; 

    int i = 0; 
    for (String s : a1) 
     matches[i++] = a2.contains(s) ? 1 : 0; 

    System.out.println(Arrays.toString(matches)); 
} 

wyjściowa:

[0, 0, 0, 1, 0, 1, 1] 
1

Można użyć contains(Object o) method of ArrayList aby sprawdzić, czy element jest obecny w 2. ArrayList czy nie i odpowiednio dodać element do listy 3rd jak:

for(String temp: a1) 
{ 
    if(a2.contains(temp)) 
    { 
     a3.add(1); 
    } 
    else 
    { 
    a3.add(0); 
    } 
} 
Powiązane problemy