【问题标题】:Beginner Java remove object in an ArrayList Java Issue初学者 Java 删除 ArrayList Java 问题中的对象
【发布时间】:2020-07-03 01:39:44
【问题描述】:

我很难弄清楚为什么会这样,当我从我的 arrayList 调用特定对象时,它没有返回我想要的输出?我被要求创建 3 个新对象并使用 add 方法将它们添加到数组列表中,在 4 处使用 get 调用无效参数,在 2 处调用有效参数,显示详细信息然后删除 4 和 2。我得到的输出从我的主要方法是

Invalid index position
2
The current guests in Puss in Boots Cattery:
Garfield
Bob
John
Invalid index position
The current guests in Puss in Boots Cattery:
Garfield
John

我不明白为什么我只得到“2”作为我的输出,而不是应该存储在 2 中的猫名“John”?

package pkg4;

import java.util.ArrayList;

public class Cattery {  
    private ArrayList<Cat> catList;
    private String businessName;

    public Cattery(String businessName) {
        catList = new ArrayList<Cat>();
        this.businessName = businessName;
    }

    public void addCat(Cat newCat) {

        catList.add(newCat);
    }

    public void getCat(int index) {
        if ((index >= 0) && (index <= catList.size() - 1)) {
            Cat oneCat = catList.get(index);
            System.out.println(index);
        } else {
            System.out.println("Invalid index position");
        }
    }

    public void removeCat(int indexRemove) {
        if ((indexRemove >= 0) && (indexRemove <= catList.size() - 1)) {
            catList.remove(indexRemove);
        } else {
            System.out.println("Invalid index position");
        }
    }

    public void displayAllCats() {
        System.out.println("The current guests in Puss in Boots Cattery:");
        for (Cat catNames : catList) {
            System.out.println(catNames.getName());
        }
    }

    public static void main(String[] args) {
        Cattery allCats = new Cattery("Puss In Boots Cattery");
        Cat c1 = new Cat("Garfield", 2015, 10);
        Cat c2 = new Cat("Bob", 2020, 5);
        Cat c3 = new Cat("John", 2019, 9);
        allCats.addCat(c1);
        allCats.addCat(c2);
        allCats.addCat(c3);
        allCats.getCat(3);
        allCats.getCat(2);
        allCats.displayAllCats();
        allCats.removeCat(3);
        allCats.removeCat(1);
        allCats.displayAllCats();
    }
}

类猫

public class Cat {
    private String name;
    private int yearOfBirth;
    private int weightInKilos;

    public Cat(String inputName, int inputYearOfBirth, int inputWeigthInKilos) {
        setName(inputName);
        setYearOfBirth(inputYearOfBirth);
        setWeigthInKilos(inputWeigthInKilos);
    }

    public String getName() {
        return name;
    }

    public int getYearOfBirth() {
        return yearOfBirth;
    }

    public int getWeightInKilos() {
        return weightInKilos;
    }

    public void setName(String name) {
        if (name != null && !name.isEmpty()) {
            this.name = name;
        } else if (name == null) {
            throw new IllegalArgumentException("name cannot be null");
        } else if (name.isEmpty()) {
            throw new IllegalArgumentException("name cannot be an empty String");
        }
    }

    public void setYearOfBirth(int yearOfBirth) {
        if (yearOfBirth > 0) {
            this.yearOfBirth = yearOfBirth;
        } else {
            throw new IllegalArgumentException("year of birth cannot be negative");
        }
    }

    public void setWeigthInKilos(int weigthInKilos) {
        if (weigthInKilos > 0) {
            this.weightInKilos = weigthInKilos;
        } else {
            throw new IllegalArgumentException(" weight in kilos cannot be negative");
        }
    }
}

【问题讨论】:

    标签: java oop arraylist methods


    【解决方案1】:

    您正在打印索引。

    public void getCat(int index) {
        if ((index >= 0) && (index < catList.size())) {
            Cat oneCat = catList.get(index);                
            System.out.println(index);  // **** here ****
        }
        else{
            System.out.println("Invalid index position");
        }
    }
    

    如果你想打印猫,那么有System.out.println(oneCat);


    请注意,该方法一开始就有缺陷,因为它是一个 getter 方法,因此它不应该打印 Cat,而是return 一个:

    public Cat getCat(int index) {
        if ((index >= 0) && (index < catList.size())) {
            Cat oneCat = catList.get(index);                
            return oneCat;
        } else{
            // you really should *throw* an exception here
        }
    }
    

    然后你可以在你的 main 方法中做:

    try {
        System.out.println(allCats.getCat(2));
    } catch (IllegalArgumentException e) {
        e.printStacktrace();
    }
    

    一些关键点:

    • 您当前的代码可以分为逻辑类,那些持有您正在处理的问题的“模型”,这里是 Cat,以及 UI 或“用户界面”类,那些处理从用户和将信息返回到相同的位置
    • 您的 logical 类中不应包含 UI 代码,这意味着您不应在这些类中获取或返回来自或返回给用户的输入。没有println,没有扫描仪,什么都没有。唯一的例外是,如果您使用 System.out.println 作为临时“穷人的调试器”——在程序运行时打印出关键变量的状态,最终计划在成品中删除这些语句
    • 用户输入和输出应该在您的 UI 类中分开,或者对于像这样的非常简单的程序,在 main 方法中。
    • 任何getter 方法都应该这样做——获取并返回请求的信息。你的被标记为void 并打印出数据,这使得该方法在长期方案中相当无用。
    • 为逻辑类提供public String toString() 覆盖,允许您测试和输出对象的状态。一开始,您会将这些用于程序的输出,但在您以后的学习中,它们将更多地用于调试目的。

    【讨论】:

    • 非常感谢气垫船!! toString() 覆盖确实为我在 arrayList 中的第三个对象提供了我想要的输出!继续表现出色并教育我们睡眠不足的学生:)
    【解决方案2】:

    如果要打印cat对象,请通过以下方式覆盖Cat类中的toString方法:

        @Override
        public String toString() {
            return "Cat{" +
                    "name='" + name + '\'' +
                    ", yearOfBirth=" + yearOfBirth +
                    ", weightInKilos=" + weightInKilos +
                    '}';
        }
    

    ,并更新此代码以打印 cat 对象

    public void getCat(int index) {
        if ((index >= 0) && (index < catList.size())) {
            Cat oneCat = catList.get(catList.get(index));                
            System.out.println(oneCat);
        }
        else{
            System.out.println("Invalid index position");
        }
    }
    

    【讨论】:

    • 是的,完全正确。 1+
    猜你喜欢
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2015-08-05
    相关资源
    最近更新 更多