私はリストのリストを持っており、重複することなくリストを追加したいと思います。それ以外の場合は、そのリストがすでにメインリストに含まれているかどうか確認したいと思います。私はMain
の内容を印刷するとき、私はtemp
とtemp1
の両方を得る。このような何かArrayListに別のArrayListが要素として含まれているかどうかを確認する
import java.util.ArrayList;
public class Test{
public static void main(String [] args)
{
ArrayList<ArrayList<String>> Main = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
temp.add("One");
temp.add("Two");
temp.add("Three");
Main.add(temp);// add this arraylist to the main array list
ArrayList<String> temp1 = new ArrayList<>();
temp1.add("One");
temp1.add("Two");
temp1.add("Three");
if(!Main.containsAll(temp1)) // check if temp1 is already in Main
{
Main.add(temp1);
}
}
}
を書かれています。これをどうすれば解決できますか?
contains
が
AbstractList
の方法
equals
は、その内容及びここでの含有量を比較するため、ここで
temp.equals(temp1)
戻り
true
ような場合であろう提供
ArrayList
等しい
ArrayList
のインスタンスをチェックするため、メソッド
List#contains()
を使用することができ
'Main.add(new ArrayList(temp));'を実行する必要があります。 tempを直接追加するとtemp変数(オブジェクト)への参照が設定されますが、これはあなたが望むものではありません。 –
progyammer