PHP 的数组实际上不是数组,它们是哈希表。Java 的版本是HashMap。
HashMap<String, String> data = new HashMap<String, String>();
data.put("Name", "John");
// etc.
System.out.println(data.get("Name"));
您还应该研究类,因为非 PHP 程序员通常会这样做:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
// etc.
}
然后:
class SomeClass {
public static void main(String[] args) {
Person person = new Person("John", 16);
HashMap<String, Person> people = new HashMap<String, Person>();
people.put(person.getName(), person);
}
}
类可以使大型项目的事情变得更加简单,因为它们可以做的不仅仅是保存值:
class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
/**
* Returns a person's full name (first and last name), without
* storing it as a seperate variable internally.
*/
public String getName() {
return this.firstName + " " + this.lastName;
}
public String getFirstName() {
return this.firstName;
}
// etc.
}
另外,您可以获得类型安全性。在编译时发现问题要好得多,因为您可以在部署应用程序之前解决它们,而不是之后。