[英]Nested ArrayList Object and Binary Search
如果我有一個對象的ArrayList,它也包含另一個ArrayList作為元素,那么如何聲明它並立即對其進行初始化,以及如何使用Binarysearch。 我想做的是在1行初始化,而不必聲明obj2類型的arrayList並將int存儲在另一個變量中。 對於二進制搜索,我不勝其煩。
import java.util.*;
public class nested{
public static void main(String[] args)
{
//im thinking something like this
ArrayList<obj1> ex1 = new ArrayList<>();
ex1.add(new obj1("exa1","exb1", new ArrayList<obj2> ) //this are giving me errors
ex1.add(new obj1("exa2","exb2", new ArrayList<obj2> )
ex1.add(new obj1("exa3","exb3", new ArrayList<obj2> )
Collections.sort(ex1);
int a = Collections.binarySearch(ex1,new obj1("exa1",null, new ArrayList<obj2>)) ;
}
//obj1 class with 2 string elements and 1 arraylist of type obj2
public class obj1 implements Comparable
{
String a;
String b;
ArrayList<obj2> myobj2
public obj1(String a, String b, ArrayList<obj2> myobj2)
{
this.a = a;
this.b = b;
this.myobj2 = myobj2;
}
public String geta(){return a;}
public String getb(){return b;}
public ArrayList<obj2> getmyobj2(){return myobj2;}
public int compareTo(Object anB)
{
return getb().compareTo(((obj1)anB).getb());
}
}
//obj2 class that stores a string
public class obj2 implements Comparable
{
String c;
public obj2(String c)
{
this.c = c;
}
public String getc(){return c;}
public int compareTo(Object myC)
{
return getc().compareTo(((obj2)myC).getc());
}
}
public class Acomparator implements Comparator<obj1>
{
public int compare(obj1 o1, obj1 o2)
{
return o1.geta().compareto(o2.geta();
}
}
您缺少一些括號和分號。 嘗試這個:
ex1.add(new obj1("exa1","exb1", new ArrayList<obj2>() ));
ex1.add(new obj1("exa2","exb2", new ArrayList<obj2>() ));
ex1.add(new obj1("exa3","exb3", new ArrayList<obj2>() ));
Collections.sort(ex1);
int a = Collections.binarySearch(ex1,new obj1("exa1",null, new ArrayList<obj2>() )) ;
public class obj1 implements Comparable<obj1>
{
String a;
String b;
ArrayList<obj2> myobj2
public obj1(String a, String b, ArrayList<obj2> myobj2)
{
this.a = a;
this.b = b;
this.myobj2 = myobj2;
}
public String geta(){return a;}
public String getb(){return b;}
public ArrayList<obj2> getmyobj2(){return myobj2;}
public int compareTo(obj1 anB)
{
return getb().compareTo(anB.getb());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.