Java中类似JavaScript的Object数据类型?

时间:2020-12-14 16:26:39

I am experienced in JavaScript, but new to Java. In JavaScript there are "object" data types where a given variable essentially has sub-variables with their own unique values, for example:

我在JavaScript方面很有经验,但对Java很新。在JavaScript中有“对象”数据类型,其中给定变量本质上具有带有自己唯一值的子变量,例如:

var car = {type:"Fiat", model:500, color:"white"};

It is almost like an array, but not quite (JavaScript has arrays too). I am wondering if the same type of thing exists in Java? If so, how would I declare the same thing in Java? Based on my searches I can't find an object data type, but thought maybe there was something similar?

它几乎就像一个数组,但并不完全(JavaScript也有数组)。我想知道Java中是否存在相同类型的东西?如果是这样,我将如何在Java中声明相同的内容?根据我的搜索,我找不到对象数据类型,但想到也许有类似的东西?

3 个解决方案

#1


9  

While Java has a type called object, it's not what you want. Almost everything in Java is an object, and there are two ways to handle this:

虽然Java有一种叫做object的类型,但它并不是你想要的。 Java中几乎所有东西都是一个对象,有两种方法可以解决这个问题:

  1. Define a strongly-typed object with the correct properties, as a class. Javascript has a similar concept, implemented differently, but it should be recognizable:

    使用正确的属性定义强类型对象作为类。 Javascript有一个类似的概念,实现方式不同,但它应该是可识别的:

    public class Car {
        private String type;
        private int model;
        private String color;
    
        public Car(final String type, final int model, final String color) {
            this.type = type;
            this.model = model;
            this.color = color;
        }
    
        public String getType() { return this.type; }
        public int getModel() { return this.model; }
        public String getColor() { return this.color; }
    }
    
    final Car car = new Car("Fiat", 500, "white");
    
    // To get the color, you must:
    car.getColor();
    

    Add methods to get and set attributes as appropriate, methods to start, stop, drive, etc.

    添加方法以获取和设置适当的属性,启动,停止,驱动等方法。

  2. If you want a loose collection of properties without behavior or restriction, use a Map. Again, there exists a Javascript equivalent (the {x: 1, y: 2} construct without using the new keyword).

    如果您想要一个没有行为或限制的松散的属性集合,请使用Map。同样,存在Javascript等价物({x:1,y:2}构造而不使用new关键字)。

    final Map<String, Object> car = new HashMap<>();
    car.put("type", "Fiat");
    car.put("model", 500);
    car.put("color", "white");
    
    // To get the color, you:
    car.get("color");
    

    The disadvantage with this approach is that the compiler cannot enforce the types of those objects (nearly as well), and the map cannot have custom behaviors (in any reasonable way). In your example, model was a number, but this will allow you to assign anything regardless of whether it makes sense (perhaps someone keeps the data on a server and uses an HttpConnection, all of your code expecting a number explodes).

    这种方法的缺点是编译器不能强制执行这些对象的类型(几乎也是如此),并且映射不能具有自定义行为(以任何合理的方式)。在您的示例中,模型是一个数字,但这将允许您分配任何内容,无论它是否有意义(可能有人将数据保存在服务器上并使用HttpConnection,所有代码都期望数字爆炸)。

In Java, the first method is recommended if you know you'll have multiple cars, all with the same (or similar) properties. It allows the compiler to both enforce and optimize for the properties that you know will exist, and inheritance allows you to add additional properties later. The class also allow you to define methods which operate on that instance, which can help create abstraction between parts of the system (you don't need to know how a car starts, you just tell the car to start itself).

在Java中,如果您知道您将拥有多个具有相同(或类似)属性的汽车,则建议使用第一种方法。它允许编译器对您知道将存在的属性执行和优化,并且继承允许您稍后添加其他属性。该类还允许您定义在该实例上运行的方法,这可以帮助在系统的各个部分之间创建抽象(您不需要知道汽车如何启动,您只需告诉汽车启动它)。

For reference, the Javascript equivalents are:

作为参考,Javascript等价物是:

// #1
var Car = function(type, model, color) {
    this.type = type;
    this.model = model;
    this.color = color;
}

var car = new Car("Fiat", 500, "white");

// #2
var car = {type: "Fiat", model: 500, color: "white"};

// For either option, to get the color you can simply:
console.log(car.color);

What should stand out most obviously is that Java keeps track of what type each variable is. Not visible is that Java will prevent you from assigning to unknown properties, say car.mileage, where Javascript will happily add a new property. Finally, Java has a concept of visibility, and makes things private (invisible to outside viewers) by default. Replicating that in Javascript would look something like:

最明显的是,Java会跟踪每个变量的类型。不可见的是Java会阻止你分配给未知的属性,例如car.mileage,其中Javascript将很乐意添加一个新属性。最后,Java具有可见性概念,并且默认情况下将内容设置为私有(对外部查看者不可见)。在Javascript中复制它看起来像:

var Car = function(type, model, color) {
    var _type = type;
    var _model = model;
    var _color = color;

    this.getType = function() { return _type; }
    this.getModel = function() { return _model; }
    this.getColor = function() { return _color; }
}

console.log(car.getColor());

In Javascript, you take advantage of closure to hide data. Java defaults to hidden, and requires you to expose data when you need to. It's an interesting choice, very relevant when comparing code-bases, and can help keep classes independent of one another. It's also very easy (and tempting) to violate when you start writing in OO languages, so something to keep in mind (using simple structs will come back to haunt you).

在Javascript中,您可以利用闭包来隐藏数据。 Java默认为隐藏,并要求您在需要时公开数据。这是一个有趣的选择,在比较代码库时非常相关,并且可以帮助保持类彼此独立。当你开始用OO语言写作时,这也很容易(和诱人)违反,所以要记住一些事情(使用简单的结构会回来困扰你)。

#2


1  

Yes, they are called Objects and defined by Classes. It's basically the first thing you learn when learning Java

是的,它们被称为对象并由类定义。这基本上是你学习Java时学到的第一件事

//The definition of an object and it's members
public class Car { 
 String type, model, color;
}

You can then make them public to access and change them external to the class

然后,您可以将它们公开以访问并在类外部更改它们

public class Car {
 public String type, model, color;
}

And access them like so

并像这样访问它们

//Create an instance of a Car, point to it with variable c and set one of it's properties/members
 Car c = new Car();
 c.type = "Fiesta";

But allowing variables of a class to be edited externally is considered bad form in Java, generally you would add methods to access each, called accessors

但是允许在外部编辑类的变量在Java中被认为是不好的形式,通常你会添加访问每个类的方法,称为访问器

public class Car {
  private String type, model, color;

//Return the type of this object
  public String getType(){
    return type;
  }

//Set the type of this object
  public void setType(String type){
    this.type = type;
  }

  //etc
}

Then access them like so

然后像这样访问它们

 Car c = new Car();
 c.setType("Fiesta");

A class is the template you write to create objects, which are run time instances of classes.

类是您为创建对象而编写的模板,它是类的运行时实例。

#3


1  

Most nice object for this purpose it's a LinkedHashMap. You can use it like map, but on iteration it will keep keys order.

为此目的最好的对象是LinkedHashMap。您可以像地图一样使用它,但在迭代时它会保持按键顺序。

#1


9  

While Java has a type called object, it's not what you want. Almost everything in Java is an object, and there are two ways to handle this:

虽然Java有一种叫做object的类型,但它并不是你想要的。 Java中几乎所有东西都是一个对象,有两种方法可以解决这个问题:

  1. Define a strongly-typed object with the correct properties, as a class. Javascript has a similar concept, implemented differently, but it should be recognizable:

    使用正确的属性定义强类型对象作为类。 Javascript有一个类似的概念,实现方式不同,但它应该是可识别的:

    public class Car {
        private String type;
        private int model;
        private String color;
    
        public Car(final String type, final int model, final String color) {
            this.type = type;
            this.model = model;
            this.color = color;
        }
    
        public String getType() { return this.type; }
        public int getModel() { return this.model; }
        public String getColor() { return this.color; }
    }
    
    final Car car = new Car("Fiat", 500, "white");
    
    // To get the color, you must:
    car.getColor();
    

    Add methods to get and set attributes as appropriate, methods to start, stop, drive, etc.

    添加方法以获取和设置适当的属性,启动,停止,驱动等方法。

  2. If you want a loose collection of properties without behavior or restriction, use a Map. Again, there exists a Javascript equivalent (the {x: 1, y: 2} construct without using the new keyword).

    如果您想要一个没有行为或限制的松散的属性集合,请使用Map。同样,存在Javascript等价物({x:1,y:2}构造而不使用new关键字)。

    final Map<String, Object> car = new HashMap<>();
    car.put("type", "Fiat");
    car.put("model", 500);
    car.put("color", "white");
    
    // To get the color, you:
    car.get("color");
    

    The disadvantage with this approach is that the compiler cannot enforce the types of those objects (nearly as well), and the map cannot have custom behaviors (in any reasonable way). In your example, model was a number, but this will allow you to assign anything regardless of whether it makes sense (perhaps someone keeps the data on a server and uses an HttpConnection, all of your code expecting a number explodes).

    这种方法的缺点是编译器不能强制执行这些对象的类型(几乎也是如此),并且映射不能具有自定义行为(以任何合理的方式)。在您的示例中,模型是一个数字,但这将允许您分配任何内容,无论它是否有意义(可能有人将数据保存在服务器上并使用HttpConnection,所有代码都期望数字爆炸)。

In Java, the first method is recommended if you know you'll have multiple cars, all with the same (or similar) properties. It allows the compiler to both enforce and optimize for the properties that you know will exist, and inheritance allows you to add additional properties later. The class also allow you to define methods which operate on that instance, which can help create abstraction between parts of the system (you don't need to know how a car starts, you just tell the car to start itself).

在Java中,如果您知道您将拥有多个具有相同(或类似)属性的汽车,则建议使用第一种方法。它允许编译器对您知道将存在的属性执行和优化,并且继承允许您稍后添加其他属性。该类还允许您定义在该实例上运行的方法,这可以帮助在系统的各个部分之间创建抽象(您不需要知道汽车如何启动,您只需告诉汽车启动它)。

For reference, the Javascript equivalents are:

作为参考,Javascript等价物是:

// #1
var Car = function(type, model, color) {
    this.type = type;
    this.model = model;
    this.color = color;
}

var car = new Car("Fiat", 500, "white");

// #2
var car = {type: "Fiat", model: 500, color: "white"};

// For either option, to get the color you can simply:
console.log(car.color);

What should stand out most obviously is that Java keeps track of what type each variable is. Not visible is that Java will prevent you from assigning to unknown properties, say car.mileage, where Javascript will happily add a new property. Finally, Java has a concept of visibility, and makes things private (invisible to outside viewers) by default. Replicating that in Javascript would look something like:

最明显的是,Java会跟踪每个变量的类型。不可见的是Java会阻止你分配给未知的属性,例如car.mileage,其中Javascript将很乐意添加一个新属性。最后,Java具有可见性概念,并且默认情况下将内容设置为私有(对外部查看者不可见)。在Javascript中复制它看起来像:

var Car = function(type, model, color) {
    var _type = type;
    var _model = model;
    var _color = color;

    this.getType = function() { return _type; }
    this.getModel = function() { return _model; }
    this.getColor = function() { return _color; }
}

console.log(car.getColor());

In Javascript, you take advantage of closure to hide data. Java defaults to hidden, and requires you to expose data when you need to. It's an interesting choice, very relevant when comparing code-bases, and can help keep classes independent of one another. It's also very easy (and tempting) to violate when you start writing in OO languages, so something to keep in mind (using simple structs will come back to haunt you).

在Javascript中,您可以利用闭包来隐藏数据。 Java默认为隐藏,并要求您在需要时公开数据。这是一个有趣的选择,在比较代码库时非常相关,并且可以帮助保持类彼此独立。当你开始用OO语言写作时,这也很容易(和诱人)违反,所以要记住一些事情(使用简单的结构会回来困扰你)。

#2


1  

Yes, they are called Objects and defined by Classes. It's basically the first thing you learn when learning Java

是的,它们被称为对象并由类定义。这基本上是你学习Java时学到的第一件事

//The definition of an object and it's members
public class Car { 
 String type, model, color;
}

You can then make them public to access and change them external to the class

然后,您可以将它们公开以访问并在类外部更改它们

public class Car {
 public String type, model, color;
}

And access them like so

并像这样访问它们

//Create an instance of a Car, point to it with variable c and set one of it's properties/members
 Car c = new Car();
 c.type = "Fiesta";

But allowing variables of a class to be edited externally is considered bad form in Java, generally you would add methods to access each, called accessors

但是允许在外部编辑类的变量在Java中被认为是不好的形式,通常你会添加访问每个类的方法,称为访问器

public class Car {
  private String type, model, color;

//Return the type of this object
  public String getType(){
    return type;
  }

//Set the type of this object
  public void setType(String type){
    this.type = type;
  }

  //etc
}

Then access them like so

然后像这样访问它们

 Car c = new Car();
 c.setType("Fiesta");

A class is the template you write to create objects, which are run time instances of classes.

类是您为创建对象而编写的模板,它是类的运行时实例。

#3


1  

Most nice object for this purpose it's a LinkedHashMap. You can use it like map, but on iteration it will keep keys order.

为此目的最好的对象是LinkedHashMap。您可以像地图一样使用它,但在迭代时它会保持按键顺序。