创建基类类型的数组



标题不是很有暗示性,请建议更好的标题。

这个例子可以在oca-java-se O'Reilly中找到。

我有一个基类

public class Thing{
public int thingOne;
public int thingTwo;
}

在主

class MyMain{
public static void main (String[] args){
Thing[] ta;
// how do I initialize this array
// is there a tricky way to access elements rather than ta[0] ??
}
}

我很困惑。我想课程是如何创建一个类型基类数组,初始化它并从中访问元素。

最简单的方法是用给定的长度初始化数组对象,然后迭代以填充元素。一个简单的例子如下:

public class ArrayTest {
public static class Thing  {
private int thingOne;
public int getThingOne() { return thingOne; }
public void setThingOne(int thingOne) { this.thingOne = thingOne; }
private int thingTwo;
public int getThingTwo() { return thingTwo; }
public void setThingTwo(int thingTwo) { this.thingTwo = thingTwo; }
@Override
public String toString() {
return "Thing{" +
"thingOne=" + thingOne +
", thingTwo=" + thingTwo +
'}';
}
}
public static void main(String... args) {
Thing[] array = new Thing[10];
for (int i = 0; i < array.length; i++) {
Thing thing = new Thing();
thing.setThingTwo(new Random().nextInt(10));
thing.setThingTwo(new Random().nextInt(10));
array[i] = thing;
}
Arrays.stream(array).forEach(System.out::println);
}
}

首先,public class Thing(){是错误的。应该是public class Thing{

如何初始化此数组

有很多方法可以初始化数组,例如

class Thing {
public int thingOne;
public int thingTwo;
}
class MyMain {
public static void main(String[] args) {
// First way
Thing[] ta1 = new Thing[] {};
// Also
Thing[] ta2 = new Thing[] { new Thing(), new Thing() };
// Using a loop
Thing[] ta3 = new Thing[5];
for (int i = 0; i < ta3.length; i++)
ta3[i] = new Thing();
}
}

有没有一种棘手的方法可以访问元素而不是 ta[0]

如果要使用元素的索引值访问元素,则没有其他方法。但是,如果您确实需要使用索引值访问元素,有一些方法例如

import java.util.Arrays;
class Thing {
public int thingOne;
public int thingTwo;
}
public class MyMain {
public static void main(String[] args) {
Thing[] ta = new Thing[5];
for (int i = 0; i < ta.length; i++)
ta[i] = new Thing();
// Accessing the elements without index value
for (Thing t : ta) {
System.out.println(t);
}
// Another way
System.out.println(Arrays.toString(ta));
// Also
Arrays.stream(ta).forEach(System.out::println);
}
}

最新更新