📜  Java中的向量equals()方法

📅  最后修改于: 2022-05-13 01:55:18.299000             🧑  作者: Mango

Java中的向量equals()方法

Java 中 Vector 类的Java Java (Object obj)方法用于验证 Object 与向量的相等性并进行比较。仅当两个 Vector 包含具有相同顺序的相同元素时,该列表才会返回 true。

句法:

first_vector.equals(second_vector)

参数:此方法接受一个强制参数second_vector ,它指的是要与第一个 Vector 进行比较的第二个 Vector。

返回值:如果等式成立并且对象和向量都相等,则该方法返回true ,否则返回false

以下程序用于说明Java.util.Vector.elements() 方法的工作:

方案一:

// Java code to illustrate the equals() method
import java.util.*;
  
public class Vector_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Vector
        Vector vec_tor1 = new Vector(5);
  
        // Inserting elements into the table
        vec_tor1.add("Geeks");
        vec_tor1.add("4");
        vec_tor1.add("Geeks");
        vec_tor1.add("Welcomes");
        vec_tor1.add("You");
  
        // Displaying the Vector
        System.out.println("The Vector is: "
                           + vec_tor1);
  
        // Creating an empty Vector
        Vector vec_tor2 = new Vector(5);
  
        // Inserting elements into the table
        vec_tor2.add("Geeks");
        vec_tor2.add("4");
        vec_tor2.add("Geeks");
        vec_tor2.add("Welcomes");
        vec_tor2.add("You");
  
        // Displaying the Vector
        System.out.println("The Vector is: "
                           + vec_tor2);
  
        System.out.println("Are both of them equal? "
                           + vec_tor1.equals(vec_tor2));
    }
}
输出:
The Vector is: [Geeks, 4, Geeks, Welcomes, You]
The Vector is: [Geeks, 4, Geeks, Welcomes, You]
Are both of them equal? true

方案二:

// Java code to illustrate the equals() method
import java.util.*;
  
public class Vector_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty Vector
        Vector vec_tor1 = new Vector(5);
  
        // Inserting elements into the table
        vec_tor1.add(10);
        vec_tor1.add(15);
        vec_tor1.add(20);
        vec_tor1.add(25);
        vec_tor1.add(30);
  
        // Displaying the Vector
        System.out.println("The Vector is: " + vec_tor1);
  
        // Creating an empty Vector
        Vector vec_tor2 = new Vector(6);
  
        // Inserting elements into the table
        vec_tor2.add(10);
        vec_tor2.add(15);
        vec_tor2.add(20);
        vec_tor2.add(25);
        vec_tor2.add(30);
        vec_tor2.add(40);
  
        // Displaying the Vector
        System.out.println("The Vector is: " + vec_tor2);
  
        System.out.println("Are both of them equal? "
                           + vec_tor1.equals(vec_tor2));
    }
}
输出:
The Vector is: [10, 15, 20, 25, 30]
The Vector is: [10, 15, 20, 25, 30, 40]
Are both of them equal? false