简体   繁体   English

来自另一个类的Java链表访问

[英]java linked list access from another class

This code works great but I need to be able to add a type of car from another class by calling a method or something, I am really new to java and I'm guessing its a really easy fix but I've had a look around and tried a few things without any luck. 这段代码很好用,但是我需要能够通过调用方法或其他方法从另一个类中添加某种类型的汽车,我对Java真的很陌生,我猜想它确实很容易解决,但是我环顾四周尝试了几件事却没有任何运气。 So for example a class called addCar could access the linked list either in the main method or if i need to put the list in a separate class. 因此,例如,名为addCar的类可以在main方法中或者如果我需要将列表放在单独的类中来访问链接列表。

public static void main(String[] args) {
    LinkedList<String> cars;
    cars = new LinkedList<>();
    cars.add("SUV");
    Iterator<String> itr = cars.iterator();
    while (itr.hasNext()) {
         System.out.println(itr.next());}
    }
}

You can declare LinkedList<String> cars as a member of the class, then define a method where inside you can add the string you have as parameter like 您可以将LinkedList<String> cars声明为该类的成员,然后定义一个方法,在其中可以在其中添加具有参数的字符串,例如

public void addCar(String car){
    cars.add(car);
}

You can create the Car class as shown below: 您可以创建Car类,如下所示:

public class Car {

   private LinkedList<String> cars = new LinkedList<>();

   public void addCar(String car) {
      cars.add(car);
   }

   public Iterator<String> iterator() {
      return cars.iterator();
    }
 }

One important point is that from the above code, you have defined what a Car is, but you did not create any cars ie, car objects. 重要的一点是,根据上面的代码,您已经定义了Car是什么,但是没有创建任何汽车,即汽车对象。

So, if you have to create a car inside the main() , you need to use new operator (like new Car() ) and access the methods (like addCar etc..) of the car object as shown below: 因此,如果必须在main()内创建汽车,则需要使用new运算符(例如new Car() )并访问car对象的方法(例如addCar等。),如下所示:

public class YourTestClass {

    public static void main(String[] args) {
        Car car = new Car();
        car. addCar("SUV");
        Iterator<String> itr = car.iterator();
        while (itr.hasNext()) {
             System.out.println(itr.next());}
        }
    }
}

You can do something like this: 您可以执行以下操作:

import java.util.LinkedList;

public class Test {
    static class SomeClass {
        LinkedList<String> cars;

        public SomeClass() {
            cars = new LinkedList<>();
            cars.add("SUV");
        }

        public void addType(String type) {
            cars.add(type);
        }

        public LinkedList<String> getCars() {
            return cars;
        }
    }

    public static void main(String[] args) {
        SomeClass someClass = new SomeClass();
        someClass.addType("Sedan");
        //or
        someClass.getCars().add("Hatchback");
        System.out.println( someClass.getCars() );
        //[SUV, Sedan, Hatchback]
    }
}

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

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