Java 想知道数组中的类吗?
我有一个包含以下代码的脚本:Java 想知道数组中的类吗?,java,arrays,class,Java,Arrays,Class,我有一个包含以下代码的脚本: import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class app { public static int p; public static int b=0; public static int i;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class app {
public static int p;
public static int b=0;
public static int i;
public static int add;
public static List<Integer> a = new ArrayList<Integer>();
public static List<Node> c = new ArrayList<Node>();
public static void main(String[] args){
Random rand = new Random();
for( i = 0;i<=10;i++){
int random = getRandom();
if(random!=0){
a.add(random);
}else if(random == 0){
}
}
Collections.sort(a);
System.out.println(a);
for(int z = 1;z<a.size();z++){
Node n = new Node();
Node.pos=a.get(z);
System.out.println("Node pos set to "+a.get(z));
c.add(n);
System.out.println("Node at " + n.pos);
}
System.out.println("class array length " + c.size());
System.out.println("Node at index " + 0 +" has a pos of " + c.get(0).pos);
}
public static int getRandom(){
Random randd = new Random();
int randomnum = randd.nextInt(10);
if(!a.contains(randomnum)){
return randomnum;
}else if(a.contains(randomnum)){
}
return 0;
}
}
import java.io.IOException;
导入java.util.ArrayList;
导入java.util.Collections;
导入java.util.List;
导入java.util.Random;
公共类应用程序{
公共静态INTP;
公共静态int b=0;
公共静态INTI;
公共静态int-add;
public static List a=new ArrayList();
public static List c=new ArrayList();
公共静态void main(字符串[]args){
Random rand=新的Random();
对于(i=0;i节点中的pos字段是静态的,我们可以看到这一点,因为您是在类上而不是在实例上访问它。将其设置为非静态实例变量。此外,即使它是非静态字段,也应避免直接访问字段,而应使用setter和getter方法
例如,不要做:
Node n = new Node();
Node.pos=a.get(z); // a static access on the class
而是:
Node n = new Node();
n.setPos(a.get(z)); // a non-static setter method call on the instance
节点中的pos字段是静态的,我们可以看到这一点,因为您是在类而不是实例上访问它的。请将其设置为非静态实例变量。此外,即使它是非静态字段,也应避免直接访问字段,而应使用setter和getter方法
例如,不要做:
Node n = new Node();
Node.pos=a.get(z); // a static access on the class
而是:
Node n = new Node();
n.setPos(a.get(z)); // a non-static setter method call on the instance
您从未实际设置过所创建对象的属性。看起来您是出于某种原因设置了静态成员。请使用IDE的调试器自己调试它。学会这样做远比给出任何答案更有价值。您从未实际设置过所创建对象的属性。看起来您是在设置静态成员呃,出于某种原因。使用IDE的调试器自己调试它。学会这样做比给出任何答案都更有价值。如果我这样做,那么我就不能从其他类访问它?@user2680805:是的,你可以。你在实例上而不是在节点类上访问它。你访问它是错误的,并且修复了错误的东西。如果我这样做,那么我就可以无法从其他类访问它?@user2680805:是的,您可以。您在实例上访问它,而不是在节点类上。您访问它是错误的,并且修复了错误的东西。