嵌套ArrayList对象和二进制搜索

时间:2014-10-16 07:18:55

标签: java search arraylist binary

如果我有一个对象的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();
   }
}

1 个答案:

答案 0 :(得分:0)

你缺少一些paranthesis和一个分号。试试这个:

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());
    }
}