简体   繁体   English

在Java的一行中声明多个对象

[英]declare multiple objects in one line in java

I'm coding in java and I have a class Point with 3 differents constructors. 我在用Java编写代码,并且有一个Point类,其中包含3个differents构造函数。 I would like to create 3 objects with each constructor is one line. 我想创建3个对象,每个构造函数都是一行。 This is what I wrote : 这是我写的:

Point p1 = new Point();
Point p2 = new Point(0.5, 6.);
Point p3 = new Point(p2);

Is it possible to write this on a single line ? 是否可以将其写在一行上? Thanks ! 谢谢 !

You mean : 你的意思是 :

Point p1 = new Point(), p2 = new Point(0.5, 6.), p3 = new Point(p2);

I assume you have three different constructor in Point class. 我假设您在Point类中具有三个不同的构造函数。


But note, be careful, it will not work if you do : 但是请注意,请注意,如果这样做,它将无法正常工作:

Point p1 = new Point(), p3 = new Point(p2), p2 = new Point(0.5, 6.);// Error
                                       ^^   ^^ 

In this case the order is important, you have to evaluate the first Object p1 then you can create the 3rd Object p3 based on the 2nd one. 在这种情况下,顺序很重要,您必须评估第一个对象p1然后才能根据第二个对象创建第三个对象p3

Simple answer: not really. 简单答案:并非如此。

Of course, you can just avoid the line break, and put 当然,您可以避免换行并放

Point p1 = ... ; Point p2 = ...

on one line. 在一行上。 Or: 要么:

Point p1 = new Point(), p2 = new Point(0.5, 6.), p3 = new Point(p2);

turning ;+linebreak into commas. 将; + linebreak变成逗号。

And just for the record: alone the fact that you are naming things "point1, point2, point3" is indicating that you are probably doing something wrong. 仅作记录:仅将名称命名为“ point1,point2,point3”这一事实就表明您可能在做错事。 Putting an index into the variable name basically means that you should rather use an array, list, or map. 将索引放入变量名基本上意味着您应该使用数组,列表或映射。

The other important thing: your intention is always always always to write code that is easy to read and understand for other humans. 另一个重要的事情是:您的意图总是总是编写易于被其他人阅读和理解的代码。 Stuffing more information into a single line is (very often) not helping with this goal. 更多信息填充到一行中(通常)对实现该目标没有帮助。

当然。

Point p1 = new Point(), p2 = new Point(0.5, 6), p3 = new Point(p2);

You can write each statements in a single line seperated by semi colon . 您可以将每个语句写在用半冒号分隔的一行中。

Point p1 = new Point(); Point p2 = new Point(0.5, 6.); Point p3 = new Point(p2);

or 要么

Point p1 = new Point(), p2 = new Point(0.5, 6.), p3 = new Point(p2);

So line breaks can be avoided in java. 因此在Java中可以避免换行。

If you use scala , then concept of case classes can be used to achieve your expectation . 如果使用scala ,则可以使用case classes概念来达到您的期望。 In scala we don't need to use new keyword to instantiate an object . 在Scala中,我们不需要使用new关键字来实例化对象。 You can create the instannce directly as 您可以直接创建实例

val p1 = Point() or val p2 = Point(0.5,6.) or val p3 = Point(p2) . val p1 = Point()val p2 = Point(0.5,6.)val p3 = Point(p2)

But you should have a suitable case class Point for this . 但是您应该为此设置一个合适的案例类 Point

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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