can not compare two arraylist object - java

import java.util.ArrayList;
import java.util.List;
public class arr {
public arr () {
// creat empty list
List<Integer> alpha = new ArrayList<>();
}
public static void main (String []args ) {
arr com1 = new arr();
arr com2= new arr();
//returning false but should be true the two are empty array
com1.equals(com2);
}
}
I am trying to create a class that can build a an empty array but when I am trying to compare the two-object its returning false , but the two have an empty arraylist so it should return true

You are trying to call a missing method called isEmpty().
You also need to move the list alpha as a field for the class, so that it can be accessed by the isEmpty() method.
To check for equality, just overload the equals() method.
Also as #Billy mentioned, you should override the hashCode too (so that it'll still work if you use hashSet/hashMap to store the arr class later on in your codes)
import java.util.ArrayList;
import java.util.List;
public class arr {
List<Integer> alpha = new ArrayList<>();
//creates the isEmpty method
boolean isEmpty() {return alpha.isEmpty();}
//check if two arr classes are the same
#Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass())
return false;
arr other = (arr) obj;
//checks if the alpha of this is the same as the alpha in obj
return alpha.equals(other.alpha);
}
//also override the hashCode method so that it'll work correctly for hash containers like hashMap and hashSet.
#Override
public int hashCode(){ return alpha==null?0: alpha.hashCode(); }
public static void main (String []args ) {
arr com1 = new arr();
arr com2= new arr();
//calling the isEmpty() method from the main.
System.out.println("com1 Empty? =" +com1.isEmpty());
//checks if com1 and com2 are equal
System.out.println("com1 same as com2? =" +com1.equals(com2));
}
}

You can use size() method to check Arraylist size. Checkout this for further reference: https://www.geeksforgeeks.org/arraylist-size-method-in-java-with-examples/

Your code is syntactically wrong.
class arr
Java convention says class names should be nouns, in mixed case with the first letter of each internal word capitalized. So lets assume it is named as ArrCreator
arr() is a method, so:
it must have a return type
it cannot be accessed in a static way, should be through an instance of ArrCreator class
since it create an empty List, not a empty Array, let renamed it to createEmptyList()
Naming still messy, but now at lest you can see it compiling (I hope)
import java.util.ArrayList;
import java.util.List;
public class ArrCreator
{
public List<Integer> createEmptyList()
{
// create empty list
List<Integer> alpha = new ArrayList<>();
return alpha;
}
public static void main(String[] args)
{
ArrCreator creator = new ArrCreator();
List<Integer> com1 = creator.createEmptyList();
List<Integer> com2 = creator.createEmptyList();
System.out.println(com1.equals(com2));
}
}
output: true

Related

Java ArrayList add class object to list if object name is not already in the list?

I have looked through other questions but cant seem to find the answer I am looking for.
I am having trouble figuring out how to create a loop that adds a class object to an ArrayList only if it its name is not used in the list already.
This is the class I have.
package myPackage;
public class Cube {
private int length;
private String name;
public Cube(int initLength, String initName) {
this.length = initLength;
this.name = initName;
}
I would like to create new cubes and add them to a list. Here is the code I am trying to do this with.
In the while loop I can't figure out how to determine if the name has been used or not
package myPackage;
import java.util.ArrayList;
import java.util.Scanner;
public class PartFive {
public static void main(String[] args) {
ArrayList<Cube> cubelist = new ArrayList<>();
Cube oshea = new Cube (13, "oshea");
Cube mike = new Cube (7, "tony");
cubelist.add(oshea);
cubelist.add(mike);
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("enter cube name (blank quits): ");
String name = reader.nextLine();
if (name.equals("")){
break;
}
System.out.println("enter side length: ");
int length = Integer.valueOf(reader.nextLine());
Cube newcube = new Cube(length, name);
if(cubelist.contains(newcube.name)) {
// dont add to list
}
else {
cubelist.add(newcube);
}
}
reader.close();
System.out.println(cubelist);
}
}
Any constructive criticisms and suggestions are welcomed.
Replace
if(cubelist.contains(newcube.name)) {
dont add to list
}
else {
cubelist.add(newcube);
}
with
boolean found = false;
for(Cube cube: cubelist){
if(cube.getName().equals(name)) {
found = true;
break;
}
}
if(!found) {
cubelist.add(newcube);
}
The idea is to use a boolean variable to track if a cube with the same name as that of the input name already exists in the list. For this, iterate cubelist and if a cube with the same name as that of the input name is found, change the state of the boolean variable and break the loop. If the state of the boolean variable does not change throughout the loop, add the cube to the list.
From the code in your question:
if(cubelist.contains(newcube.name)) {
// don't add to list
}
else {
cubelist.add(newcube);
}
Method contains in class java.utilArrayList is the way to go but you need to be aware that method contains [eventually] calls method equals of its element type. In your case, the element type is Cube. Therefore you need to add a equals method to class Cube. I don't know what determines whether two Cube objects are equal, but I'll guess, according to your question, that they are equal if they have the same name, even when they have different lengths. I will further assume that name cannot be null. Based on those assumptions, here is a equals method. You should add this method to class Cube.
public boolean equals(Object obj) {
boolean areEqual = false;
if (this == obj) {
areEqual = true;
}
else {
if (obj instanceof Cube) {
Cube other = (Cube) obj;
areEqual = name.equals(other.name);
}
}
return areEqual;
}
Now, in method main of class PartFive you can use the following if to add a Cube to the list.
if (!cubelist.contains(newcube)) {
cubelist.add(newcube);
}
You can check for duplicate names in the cubelist array using lambda expressions (for better readability):
boolean isNameAlreadyExisting = cubelist.stream()
.anyMatch(cube -> cube.getName().equals(newcube.getName())); // this is returning true if any of the cubelist element's name is equal with the newcube's name, meaning that the name is already existing in the cubelist
if (!isNameAlreadyExisting) {
cubelist.add(newcube);
}
One thing that you should do is to remove the while(true) instruction which causes an infinite loop.
Another suggestion is to display the name of objects contained by cubelist, to see that indeed the names are not duplicated:
cubelist.stream()
.map(Cube::getName)
.forEach(System.out::println);

Add method for multiple arrays and ToString?

I'm having trouble understanding what exactly I would put in one of my classes to create the add method for 3 Arrays of the same Type. Here are the generic arrays in the main class
ArrayContainer<Integer> numberContainer = new ArrayContainer<>();
ArrayContainer<String> wordContainer = new ArrayContainer<>();
ArrayContainer<Pokemon> pokedex = new ArrayContainer<>();
My constructor for ArrayContainer is
public ArrayContainer(){
container = (T[]) new Object[defaultSize];
numItems = 0;
}
In my separate class, I'm confused what to put for my
public void add (T item){}
and I'm confused as what to return within my toString. I know you add to an array by putting
arrayName[index] = whatever;
But what would I put in that add method that would add to whatever array I call the method on? Would it be container[index] = item;?
What should I return that would return the element in the array?
Since the number of items in your ArrayContainer is not known beforehand, you should use a dynamic array, also known as List.
The numItems then becomes redundant since you can get it by calling list.size()
Your add function will only need to call list.add. As noted in the comments, it seems you're re-writing/wrapping List
In your toString method, you can return a string that concatenates all results of toString of the items included. StringBuilder can help you create a "format" that suits you. Of course this means that the objects you're putting in the container need to implement toString
Combining all the things will give you something like this:
ArrayContainer
public class ArrayContainer<T> {
private List<T> items;
public ArrayContainer() {
items = new ArrayList<>();
}
public void add(T item) {
items.add(item);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (T it: items)
sb.append(it.toString()).append(' ');
sb.append(']');
return sb.toString();
}
}
Main
public class Main {
public static void main(String[] args) {
ArrayContainer<String> stringArrayContainer = new ArrayContainer<>();
stringArrayContainer.add("hello");
stringArrayContainer.add("world");
System.out.println(stringArrayContainer);
// Outputs: [hello world]
}
}

ArrayList calling method

import acm.program.*;
import java.util.*;
public class ReverseArrayList extends ConsoleProgram {
public void run() {
println("This program reverses the elements in an ArrayList.");
println("Use 0 to signal the end of the list.");
ArrayList<Integer> list = readArrayList();
reverseArrayList(list);
printArrayList(list);
}
/* Reads the data into the list */
private ArrayList<Integer> readArrayList() {
ArrayList<Integer> list = new ArrayList<Integer>();
while (true) {
int value = readInt(" ? ");
if (value == 0) break;
list.add(value);
}
return list;
}
I dont understand the following code:
ArrayList<Integer> list = readArrayList();
I dont understand why I can't do the following instead:
list.getInput();
Why do i need to make the ArrayList equal to the method, and this confuses me because now I'm unsure which way is needed whenever I want to call a method in java
Your code shows that the method getInput() does not take in an ArrayList as argument, but returning it instead. So it is reasonable that
Arrlist=getInput()
Is the correct syntax, you are assigning the returned ArrayList from getInput() to Arrlist. While on the other hand,
Arrlist.getInput()
represents a method that must be implemented in ArrayList Class or one of its superclasses, which is not true in your case. I would recommend revising OOP concepts.
One way you might be able to pass it is using a constructor. I mocked up working code that does the same.
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ArrayListExample {
ArrayList<Integer> ofNumbers;
public ArrayListExample() {
ofNumbers = new ArrayList<>();
createArray();
}
private void createArray(){
ofNumbers = IntStream.range(0, 10)
.boxed()
.collect(Collectors
.toCollection(ArrayList::new));
}
public ArrayList<Integer> getInput() {
return ofNumbers;
}
public void getArray() {
ArrayList<Integer> newList = new ArrayList<>(ofNumbers);
for (Integer num : newList) {
System.out.println(num);
}
}
}
I also agree with Andrew. Keep it up, with a little more practice this will become second nature to you.

How to compare two Integers in java

I want to compare elements in two list using < > ==
Is it the right way to use intValue()?
List<Integer> a = new ArrayList<Integer>();
a.add(129);
List<Integer> b = new ArrayList<Integer>();
b.add(128);
if(a.get(0).intValue() > b.get(o).intValue()) {
// something
}
You're making it the right way.
As stated in the comments, you could also you compareTo().
An alternative to compareTo() is equals() which won't throw a NullPointerException in the case where the object is null.
Your way is correct. But with a small correction.
1)
a.get(0).intValue() == b.get(0).intValue()
2)
a.get(0).equals(b.get(0))
This is the problem in your code, you have to get(0), instead of get(1). Remember, in java it always start with 0.
Values can be compared using equals() or CompareTo method as well.
import java.util.ArrayList;
import java.util.List;
public class TestClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> a= new ArrayList<Integer>();
a.add(128);
List<Integer> b = new ArrayList<Integer>();
b.add(128);
if(a.get(0).intValue() == b.get(0).intValue()){
System.out.println("success");
}else{
System.out.println("failure");
}
if(a.get(0).equals(b.get(0))){
System.out.println("success");
}else{
System.out.println("failure");
}
}
}

How to make a set of arrays in Java?

Since the equals function in array only check the instance, it doesn't work well with Set.
Hence, I wonder how to make a set of arrays in Java?
One possible way could be put each array in an object, and implement equals function for that class, but will that decrease the performance too much?
Don't use raw Arrays unless you absolutely have to because of some legacy API that requires an Array.
Always try and use a type safe ArrayList<T> instead and you won't have these kind of issues.
If you make your Set be an instance of TreeSet, you can specify a custom Comparator which will be used for all comparisons (even equality).
You could create a wrapper class for your array and override hashcode and equals accordingly.
For example:
public class MyArrayContainer {
int[] myArray = new int[100];
#Override
public boolean equals(Object other) {
if (null != other && other instanceof MyArrayContainer) {
MyArrayContainer o = (MyArrayContainer) other;
final int myLength = myArray.length;
if (o.myArray.length != myLength) {
return false;
}
for (int i = 0; i < myLength; i++) {
if (myArray[i] != o.myArray[i]) {
return false;
}
}
return true;
}
return false;
}
#Override
public int hashCode() {
return myArray.length;
}
}
Since Java 9, you can use Arrays::compare method as a comparator for TreeSet that compares the contents of arrays.
Set<String[]> set = new TreeSet<>(Arrays::compare);
String[] val1 = {"one", "two"};
String[] val2 = {"one", "two"};
String[] val3 = {"one", "two"};
set.add(val1);
set.add(val2);
System.out.println(set.size()); // 1
System.out.println(set.contains(val1)); // true
System.out.println(set.contains(val2)); // true
System.out.println(set.contains(val3)); // true
See also: Check if an array exists in a HashSet<int[]>
It is better to use lists for this problem.
Also, use trusted sources to ensure that Java is properly configured on your system; Read the complete information in the documentation
Since the ArrayList class already wraps an array, you can extend it and override the equals and hashCode methods. Here is a sample:
public MyArrayList extends ArrayList<MyClass> {
#Override
public boolean equals(Object o) {
if (o instanceof MyArrayList) {
//place your comparison logic here
return true;
}
return false;
}
#Override
public int hashCode() {
//just a sample, you can place your own code
return super.hashCode();
}
}
UPDATE:
You can even override it for a generic use, just changing the code to:
public MyArrayList<T> extends ArrayList<T> {
//overrides the methods you need
#Override
public boolean equals(Object o) {
if (o instanceof MyArrayList) {
//place your comparison logic here
return true;
}
return false;
}
}
A class that extends Set and override the equals method could do it.

Categories

Resources