[英]how array of object behave when the elments are of diiferent types
,,, ,,,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Try {
public static void main(String[] args) {
String [] a = new String [5];
a[0]="0";
a[1]="1";
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList(a));
for(List l : list)
{
System.out.println(l.get(0));
}
Object [] s = new Object[5];
Object [] d = new Object[10];
d[0]=10;
d[1]=10;
d[2]="me";
d[3]=new Integer(3);
d[4]=new person();
d[5]= 'x';
for(Object i : d)
{
System.out.println(i);
}
System.out.println(new person().toString());
}
static class person {
String name = "my name";
int age = 50;
public person()
{
name ="new name";
}
@Override
public String toString()
{
return name + "\n" + age;
}
}
}
,,, ,,,
i was expecting that when you create an array of objects and print it with casting it will print out hashcode.. but this code above printed the value as if it would if it was casted any idea if this a new java feature??我期待当您创建一个对象数组并使用强制转换打印它时,它会打印出哈希码。但是上面的代码打印的值就好像它被强制转换一样,如果这是一个新的 java 功能?
System.out.println(x)
will call x
's toString()
method. System.out.println(x)
将调用x
的toString()
方法。 Unless overridden, that method will print out the object's location in memory.除非被覆盖,否则该方法将打印出对象在 memory 中的位置。 You have overridden it.你已经覆盖了它。 This is because subclass methods are "retained" even if assigned to a superclass.这是因为即使分配给超类,子类方法也会“保留”。
class Foo {
public int run() {
return 1;
}
}
class Baz extends Foo {
@Override
public int run() {
return 2;
}
}
...
Foo f = new Baz();
f.run(); // >>> 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.