JavaRush /Java Blog /Random EN /Coffee break #176. Similarities and differences between A...

Coffee break #176. Similarities and differences between Array and ArrayList. How to Write an Effective equals() Method

Published in the Random EN group

Similarities and differences between Array and ArrayList

Source: Medium This article focuses on understanding the concepts of Array and ArrayList and the differences between them. Coffee break #176.  Similarities and differences between Array and ArrayList.  How to write an efficient equals() method - 1

Java Array

An Array is a data structure that allows you to store an ordered sequence of values ​​of the same type. For example, you can create an array of characters, numbers, and so on. This applies to all primitive types and even objects like String . Once the array is created, we cannot change its size. Here's a general example of declaring an array reference variable and allocating the array:
dataType[] arrayName = new dataType[numElements];
If we try to add more than the size of the array, we get an ArrayIndexOutOfBoundsException .

Array Declaration

To declare an array, use [ ] characters after the data type. They indicate that the variable is a reference to an array. An array reference variable can refer to arrays of various sizes. The new keyword creates space in memory to store an array with a specified number of elements. An array reference variable is assigned to refer to this newly allocated array. The following example declares an array reference variable gameScores , allocates an array of four integers, and assigns gameScores to refer to the allocated array.
int[] gameScores = new int[4];
Array elements are automatically initialized to default values ​​when you use the new keyword to initialize an array reference. The default value for elements of integer and floating-point data types is zero, and the default value for Boolean elements is false . You can also declare an array reference variable without immediately allocating the array, and then assign the variable with the allocated array.
int[] gameScores;

gameScores = new int[4];

Initializing an Array with Non-Default Values

You can initialize array elements with non-default values ​​by specifying the initial values ​​in curly braces {} separated by commas.
int [] myArray = { 5 , 7 , 11 };
The example above creates an array of three integer elements with the values ​​5, 7, and 11. This array initialization does not require the use of the new keyword because the size of the array is automatically set to the number of elements in the curly braces. For large arrays, initialization can be accomplished by first defining the array and then using a loop to assign the elements of the array. Array elements can be accessed using their zero-based indices.
Int[ ] intArray = new int [ ] {2};
intArray [0] = 1;
intArray [1] = 2;

ArrayList

An ArrayList is an ordered list of elements of a resizable reference type . It is also a class from the java.util package belonging to the Java Collection Framework. ArrayList provides us with dynamic arrays and automatically handles resizing them. As you add elements to the ArrayList, its memory size automatically increases. You can use an ArrayList using the import java.util.ArrayList; . We can also create an ArrayList instance using the following statement:
ArrayList<Type> arrayList = new ArrayList<Type>();
The ArrayList can grow in size to accommodate the elements it needs. ArrayList does not support primitive types such as int , but rather reference types such as Integer . A common mistake among beginners is to declare an ArrayList of a primitive type such as int , as in ArrayList<int> myVals . This results in a compilation error: “unexpected type, found : int, required: reference”. Example: Let's create an ArrayList object named cars , which will store the strings:
import java.util.ArrayList;

ArrayList<String> cars = new ArrayList<String>();
To add elements to an ArrayList , use the add() method . To access an element of an ArrayList , the get() method is used .
cars.add("Tesla");
cars.add("BMW");
cars.add("Kia");
cars.get(0);
The difference between a built-in array and an ArrayList in Java is that in the first case, the size of the array cannot be changed (if you want to add or remove elements to/from the array, you need to create a new one). Whereas in an ArrayList , elements can be added and removed at any time.

Similarities Between Array and ArrayList

  • Array and ArrayList are used to store elements.
  • Array and ArrayList can store null values.
  • Both processes occur in constant time.
  • They may have duplicate values.
  • Array and ArrayList do not guarantee the presence of ordered elements.

Key Differences Between Array and ArrayList

The main difference between an array ( Array ) and an ArrayList is the static nature of an array and the dynamic nature of an ArrayList . Once created, you cannot change the size of the array, whereas an ArrayList can change its size as needed. Another important difference is that an array is a basic functionality provided by Java. On the other hand, ArrayList is a part of the collections framework in Java. We can access the elements of an array using a square bracket in which we can specify an index. While there is a set of methods to access the elements of the ArrayList and change them. Even though they are different, both of them are nevertheless comparable in other respects. Both of these data structures in Java are based on indexes and allow you to store objects. Additionally, they allow null values ​​and duplicates. If you know the size of the objects in advance, then it is better to use an array. But if you are not sure about the size, then you should use ArrayList instead .

How to Write an Effective equals() Method

Source: Medium This post will help you better understand the use of the equals() method when working with Java code. If we talk about the default equals() method and without any implementation, then it is in many ways similar to the == operation . That is, this method compares objects. For example, equals() compares two strings and returns true if the strings are equal and false if they are not. Please note that the == operator is not recommended for comparing objects in Java. The reason is that when comparing objects, == will only return true if the references point to the same object. The easiest way to avoid problems is to not override the equals method , in which case each instance of the class is equal only to itself. You only need to override equals when the class has a concept of logical equality that is different from the simple identity of the object, and the superclass has not yet overridden equality. Thus, when using the equals() method , you need to find out whether object references are logically equivalent and whether they refer to the same object.

Properties of the equals method

Each equals method implements an equivalence relation . It has the following properties:
  • Reflexive : For any non-null reference value x, x.equals (x) must return true .

  • Symmetric : For any non-null reference values​​x and y , x.equals(y) must return true only if y.equals(x) returns true .

  • Transitive : For any non-null reference values ​​x , y , z , if x.equals(y) returns true and y.equals(z) returns true , then x.equals(z) must also return true .

  • Consistent : For any non-null reference values ​​x and y, multiple calls to x.equals(y) must consistently return true or consistently return false .

  • Non-nullity : For any non-null reference value x, x.equals (null) must return false .

Let's take a closer look at each property:

Reflexivity:

An object must be equal to itself. To verify this, add an instance of your class to the collection. The contains method may well indicate that the collection does not contain the instance you just added.

Symmetry:

Two objects (they can be from different classes) must be equal to each other.

Subsequence:

Don't write an equals method that depends on unreliable/volatile resources.

Non-zero:

Always returns true if the object passed to equals is null .

Let's summarize:

Here's a recipe for a quality equals method :
  1. Use the == operator to test whether an argument is a reference to this object.

  2. Use the instanceof operator to check if an argument is of the correct type.

  3. Cast the argument to the correct type.

  4. For each “significant” field in a class, check whether that argument field matches the corresponding field of that object:

    • For primitive fields: whose type is not float or double , use the == operator for comparisons.
    • For object reference fields: call the equals method recursively; for floating point fields use the static method Float.compare(float, float); and for double fields use Double.compare(double, double) .
    • For array fields: Apply these guidelines to each element. If every element in an array field is significant, use one of the Arrays.equals() methods .
    • Some object reference fields may contain null values . To avoid throwing a NullPointerException , check such fields for equality using the static method Objects.equals(Object, Object) .
  5. When you finish writing your equals method , ask yourself three questions: Is it symmetric? Is it transitive? Is he consistent?

And remember, always override hashCode when overriding equals .
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION