在《thinking in java》这本书中,11章练习7中,要求创建一个类,然后创建一个用你的类的对象进行过初始化的数组。这涉及到用过两个类来初始化一个数组。
首先,创建一个类
class E07_GenerateString { private static int counter; private int count=counter++; public String toString(){ return "E07_GenerateString" +count; } }
其次,再创建一个类,通过循环进行数组的创建。
public class E07_TestList { public static void main(String[] args) { E07_GenerateString[] g=new E07_GenerateString[10]; for(int i=0;i<g.length;i++){ g[i]=new E07_GenerateString(); //m.out.println(g); } List<E07_GenerateString> list=new ArrayList<E07_GenerateString>(Arrays.asList(g)); System.out.println("list "+list); List<E07_GenerateString> sub=list.subList(1, 5); System.out.println("sublist "+sub); list.remove(sub); System.out.println(list); } }
运行结果:
list [E07_GenerateString0, E07_GenerateString1, E07_GenerateString2, E07_GenerateString3, E07_GenerateString4, E07_GenerateString5, E07_GenerateString6, E07_GenerateString7, E07_GenerateString8, E07_GenerateString9] sublist [E07_GenerateString1, E07_GenerateString2, E07_GenerateString3, E07_GenerateString4] [E07_GenerateString0, E07_GenerateString1, E07_GenerateString2, E07_GenerateString3, E07_GenerateString4, E07_GenerateString5, E07_GenerateString6, E07_GenerateString7, E07_GenerateString8, E07_GenerateString9]
时间: 2024-10-25 02:32:11