Java 为什么在集合接口中添加对象时无法创建具有引用名称的对象?

Java 为什么在集合接口中添加对象时无法创建具有引用名称的对象?,java,Java,添加具有引用名称的对象时,我遇到了一个错误 class vechile { void service() { System.out.println("Generic vehicle servicing"); } } public class mechanic { public static void main(String args[]) { List vehicles = new ArrayList();

添加具有引用名称的对象时,我遇到了一个错误

class vechile
{
    void service()
    {
        System.out.println("Generic vehicle servicing");
    }
}

public class mechanic
{
    public static void main(String args[])
    {
        List vehicles = new ArrayList();
        vehicles.add(vechile q1=new vechile());// this line is showing error
        vehicles.add(new vechile());
    }
}
vehicles.add(vechile q1=new vechile())是不允许的

你可以这样做

vechile q1= null;
vehicles.add(q1=new vechile());
vehicles.add(vechile q1=new vechile())是不允许的

你可以这样做

vechile q1= null;
vehicles.add(q1=new vechile());

在java或大多数OOP语言中,当我们向数组或列表添加或放置元素时,我们不是传递变量本身,而是传递该对象的引用,因此,引用变量是什么与此无关。我们必须创建新的引用类型变量,然后在从列表中获取对象时将此对象分配给它

 List vehicles = new ArrayList();
 //vehicles.add(vechile q1=new vechile());// Irrelavent
 vehicles.add(new vechile()); // Reference is added to the list and not the variable
         or
 vechile q1=new vechile()
 vehicles.add(q1);
然后,当我们从列表中获取这些对象时,首先必须创建引用类型变量,然后分配对象

  Vehicle v1 = null;
  v1 = vehicles.get(i) //i is the index for q1.
因此,java在语法上是不允许的


希望我用java或大多数OOP语言回答了您的问题,当我们向数组或列表添加或放置元素时,我们不是传递变量本身,而是只传递该对象的引用,因此引用变量是什么与此无关。我们必须创建新的引用类型变量,然后在从列表中获取对象时将此对象分配给它

 List vehicles = new ArrayList();
 //vehicles.add(vechile q1=new vechile());// Irrelavent
 vehicles.add(new vechile()); // Reference is added to the list and not the variable
         or
 vechile q1=new vechile()
 vehicles.add(q1);
然后,当我们从列表中获取这些对象时,首先必须创建引用类型变量,然后分配对象

  Vehicle v1 = null;
  v1 = vehicles.get(i) //i is the index for q1.
因此,java在语法上是不允许的


希望我回答了您的问题,因为Java语法不允许这样做,因为Java设计师认为这样做没有用。请注意,在以后的问题中,如果您让示例代码遵循正常的命名约定等,这将非常有帮助。(因此
车辆
而不是
车辆
,以及
机械
而不是
机械
)这样就不会让人分心了。因为Java语法不允许这样做,因为Java设计人员认为这样做没有用。请注意,在以后的问题中,如果让示例代码遵循正常的命名约定等,这真的很有帮助。(因此,
Vehicle
而不是
vechile
,而
mechanical
而不是
mechanical
)这样就不会那么让人分心了。