简体   繁体   中英

Using an object array inside a method

I know what the errors are. I want to know if its possible to do something like this. (Basically looking for an alternative way of doing this but is actually correct.)

Class:

private String[] names = {"Player 1", "Player 2"};

public void setName(Object[] objectName, String name)
    for(int x = 0; x < objectName.length; x++){
        //Problem is below here, "name can not be resolved or is not a field" is doing something like this not possible?
        objectName[x].name = names[x];
    }
}

Edited to show how it would be used.

Class 2:

Public static void methodName(){
    String name;
    ClassName2[] c2 = new ClassName2[2];
    c2[0] = new ClassName2();  
    c2[1] = new ClassName2();
    c2[0].setName(c2, name);
}

In your exmaple the variable "objectName" must have the same size (or bigger) like "names". With "String name" you want to define the field/variable you want to set in the object?

Anyways, I suggest you to use ArrayList, look on the example:

public class ArrayObject {

private String[] names = {"Player 1", "Player 2"};

/**
 * @param args
 */
public static void main(String[] args) {
    ArrayList<String> myArrayList = new ArrayList<String>();
    new ArrayObject().setName(myArrayList);
}

public void setName(ArrayList<String> objectName) {
    for(int x = 0; x < names.length; x++) {
        objectName.add(names[x]);
    }

    // Testoutput
    for(int x = 0; x < objectName.size() ; x++) {
        System.out.println(objectName.get(x));
    }
}

}

ArrayList is a dynamic array where you can add as many object as you want, read them and remove any of them.

我认为您应该特别阅读泛型和有界泛型: http : //docs.oracle.com/javase/tutorial/java/generics/bounded.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM