JAVA - 在两个数组之间获得差异

时间:2015-11-14 14:43:01

标签: java arrays compare

我想比较一个custom class的两个数组,它存储一些字符串和短字符串。目的是从第二个数组中获取那些不在第一个数组中的项目。 作为一个回报,我想要一个班级的数组。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

首先,您需要在自定义类中创建一个接受同一类对象的方法,并测试插补对象是否与调用该方法的对象具有相同的值。然后只需循环遍历数组,看看对象是否等于另一个对象。这已经在String类中完成了。在String类中有一个方法  您可以使用的public abstract class DoctorOption extends JFrame implements ActionListener { JTextField myTxt = new JTextField(30); JButton submit = new JButton("Submit"); JRadioButton mywellRB = new JRadioButton("click here if you are well", true); JRadioButton myunwellRB = new JRadioButton("click here if you are unwell", false); public static void main(String[] args) { new DoctorOption() { }; } public DoctorOption() { setSize(400, 120); setTitle("Doctor Option"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); add(myTxt); add(mywellRB); add(myunwellRB); add(submit); submit.addActionListener(this); myunwellRB.addActionListener(this); mywellRB.addActionListener(this); setVisible(true); ButtonGroup buttons = new ButtonGroup(); buttons.add(mywellRB); buttons.add(myunwellRB); } public void actionPerformed(ActionEvent e) { if (e.getSource() == mywellRB) { myTxt.setText("in the pink! "); myTxt.setBackground(Color.pink); } } }

以下是比较2个String数组的示例。要使它与自定义类一起使用,只需更改数组类型并在类中创建.equals方法。

equals(String s)

编辑:

以下是如何在自定义类中使用equals方法

String[] array1={"Hello","Hi"};
String[] array2={"Hello","eat"};

for(int x=0;x<array1.length;x++){
    Boolean present=false;
    for(int y=0;y<array2.length;y++){
       if(array1[x].equals(array2[y])){
         present=true;
         break;
       }
     }
   if(!present){
      System.out.println(array1[x]);
 }
} 
相关问题