Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

java - Using contains on an ArrayList with integer arrays

I have an ArrayList<int[]>, and I add an array to it.

ArrayList<int[]> j = new ArrayList<int[]>();
int[] w = {1,2};
j.add(w);

Suppose I want to know if j contains an array that has {1,2} in it without using w, since I will be calling it from another class. So, I create a new array with {1,2} in it...

int[] t = {1,2};
return j.contains(t);

...but this would return false even though w was added to the list, and w contains the exact same array as t.

Is there a way to use contains such that I can just check to see if one of the elements of the ArrayList has the array value {1,2}?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Arrays can only be compared with Arrays.equals().

You probably want an ArrayList of ArrayLists.

ArrayList<ArrayList<Integer>> j = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> w = new ArrayList<Integer>();
w.add(1); w.add(2);
j.add(w);
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(1); t.add(2);
return j.contains(t); // should return true.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...