首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Java中无重复地向数组添加新元素

在Java中无重复地向数组添加新元素
EN

Stack Overflow用户
提问于 2011-12-02 02:17:50
回答 7查看 360关注 0票数 1

在下面的switch语句的case 5中,我希望用户从数组中输入一个学生,并从模块数组中选择一个模块,以便在不重复的情况下注册他们。任何想法/例子都会非常有用。提前谢谢。

控件类:

代码语言:javascript
复制
import java.util.Scanner;

public class Control {

public void run() {


    while (true) {
        Menu menu = new Menu();
        menu.getMainMenu();

        try {
            Scanner scan = new Scanner(System.in);

            int selection = scan.nextInt();
            switch (selection) {
                case 1:
                    for (Student student : students) {
                        System.out.print(student.getName() + " ");
                    }
                    break;
                case 2:
                    for (Module module : modules) {
                        System.out.print(module.getName() + " ");
                    }
                    break;
                case 3:
                    ...
                case 4:
                    ...
                case 5:
                    // Print out students 
                    System.out.println("select a student: ");
                    for (int i = 0; i < students.length; i++) {
                        System.out.println(i + " " + students[i]);
                    }

                    selection = scan.nextInt();

                    ############################
                    Confusion here
                    ############################

                case 6:
                    System.out.println("Goodbye!");
                    System.exit(0);
                    break;
                default:
                    System.out.println("Invalid option selected. You must enter a number between 1 & 6!");
            } // end switch

        } catch (Exception e) {
            System.out.println("Invalid entry. You must enter a number between 1 & 6");
        }
    } // end while

}
}
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2011-12-02 02:22:03

如果你想避免重复,不要使用数组或列表。使用集合。

票数 2
EN

Stack Overflow用户

发布于 2011-12-02 02:33:33

您可以使用set implementation (HashSet,LinkedHashSet)来避免重复。

或者使用ArrayList。但在这种情况下,请检查

代码语言:javascript
复制
list.contains(obj)

插入前

使用HashSet时,您将不知道插入的顺序。但是使用LinkedHashSet和ArrayList,您可以

如果需要,你可以使用

代码语言:javascript
复制
toArray()

Set或ArrayList中的函数将列表转换为数组

票数 1
EN

Stack Overflow用户

发布于 2011-12-02 02:38:02

在您的示例中,学生的标识符和唯一性测试是姓名(jane/alex/mike)。

如果使用名称作为索引的HashMap,则向HashMap添加(使用.put)将添加If new,但如果重复,则不会重复。

您可能想要考虑重写equals()和hashCode()来告诉Java如何确定两个学生是否相同。如果你有两个同名的不同学生,那么名字本身就会给你带来问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8346245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档