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");
}
}
}
Related
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
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.
I am having some trouble looping through an array with objects, inside the class. I wrote a little demo here so you can follow:
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
So, I have an array with the type Tank. Then I call the method doStuff inside the Tank class. The method takes the array and loops through it. And then I want to do stuff to every tank that is not the current instance of the class. I hope you can make sense out of my code and this description.
The problem is that I get nullPointerException for if (tanks[i].equals(this))
What am I doing wrong here?
That means that tanks[i] is null. (or that your overridden equals() method has a bug)
You need to check for that.
if you want to compare the IDs of your object you can use == instead of .equals()
doStuff(Tank tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i] == this) {
continue;
}
// Do stuff
}
}
When I run this code:
public class Tank {
public static void main(String[] args) {
Tank tanks[] = new Tank[2];
tanks[0] = new Tank();
tanks[1] = new Tank();
tanks[0].doStuff(tanks);
}
public void doStuff(Tank[] tanks) {
for (int i = 0; i < tanks.length; i++) {
if (tanks[i].equals(this)) continue;
// Do stuff
}
}
}
No error happens. Therefore, you've probably overridden .equals, and that is where the NullPointerException is occurring. The other possibility is that your simple example doesn't accurately reflect where your bug is occurring.
I have implemented a cardgame and need to test the shuffle method. I am using netbeans 7.2 and am now having a problem because the deckBeforeShuffle is empty after i call the instance.shuffleDeck method so I cant compare it with my deckAfterShuffle array to see if it is shuffled! Its the first time I am using JUnit and have tried different ways to fix this but it has all been in vain.
#Test
public void testShuffleDeck() {
System.out.println("shuffleDeck");
CardDeck instance = new CardDeck(1);
ArrayList<Card> deckBeforeShuffle = instance.getDeck();
instance.shuffleDeck();
ArrayList<Card> deckAfterShuffle = instance.getDeck();
boolean isShuffled = false;
int position = 0;
System.out.println(deckBeforeShuffle.size());
while(position<deckBeforeShuffle.size() && !isShuffled){
if(deckBeforeShuffle.get(position).getSuitValue() != deckAfterShuffle.get(position).getSuitValue() && deckBeforeShuffle.get(position).getvalue() != deckAfterShuffle.get(position).getvalue()){
isShuffled = true;
}
position++;
}
assertEquals(true, isShuffled);
}
My shuffle method!
public void shuffleDeck(){
ArrayList<Card> temp = new ArrayList();
Random rand = new Random();
int position;
while(deck.size() > 0){
position = rand.nextInt(deck.size());
temp.add(deck.remove(position));
}
deck = temp;
}
I appreciate any help!
actually it would suffice to to check for non-equality. the List's equals() method will take care of the rest.
assertFalse(deckBeforeShuffle.equals(deckAfterShuffle)); // not equal
assertEquals(deckBeforeShuffle.size(), deckAfterShuffle.size()); // but same size
assertEquals( // and same number of elements
new HashSet<Card>(deckBeforeShuffle), new HashSet<Card>(deckAfterShuffle);
And for the shuffling, you can use the existing Collections.shuffle() method. Beware, however that you have to make a copy of the list before shuffling it.
As described in this answer (and in many other sources around the Internet), there's assertArrayEquals(), which does exactly that.
I am in a beginning class for programming and try to combine 2 lists to make one list, putting the new list in numerical order. The part I am having trouble with is, allowing the code to loop, repeating the steps so that it runs through the total original loops to complete the final list which is a combination of all the numbers from the original lists. Any guidance for the loop would be appreciated. Thank you.
import inClass.list.EmptyListException;
import inClass.list.List;
public class InitialLists {
public static void main(String[] args) {
List<Integer> intObject1 = new List<Integer>();{
intObject1.insertAtFront(25);
intObject1.insertAtFront(19);
intObject1.insertAtFront(3);
intObject1.print();}
List<Integer> intObject2 = new List<Integer>();{
intObject2.insertAtFront(120);
intObject2.insertAtFront(1);
intObject2.print();}
List<Integer> combinedList = new List<Integer>();
int object1 = intObject1.removeFromBack();
int object2 = intObject2.removeFromBack();
while(intObject1.removeFromBack() != null && intObject2.removeFromBack() != null){
try {
{
if (intObject1.removeFromBack() > intObject2.removeFromBack()) {
combinedList.insertAtFront(object2);
intObject1.insertAtBack(object1);
}
else if (intObject2.removeFromBack() < intObject1.removeFromBack()) {
combinedList.insertAtFront(object1);
intObject2.insertAtBack(object2);
}
else if (intObject1.removeFromBack() == intObject2.removeFromBack()) {
combinedList.insertAtFront(object1);
}
}
combinedList.print();
object1 = intObject1.removeFromBack();
object2 = intObject2.removeFromBack();
} // end try
catch (EmptyListException emptyListException) {
emptyListException.printStackTrace();
} // end catch
} //end while
} // end main
}// end class
What about:
List<Integer> combinedList = new ArrayList<Integer>();
combinedList.addAll(intObject1);
combinedList.addAll(intObject2);
Collections.sort(combinedList);
Or am I missing something?
To merge two files / lists / streams you need a loop that looks a bit like this
WHILE NOT FINISHED
GET SMALLEST VALUE FROM INPUTS
APPEND SMALLEST VALUE TO OUTPUT
So how will you know that you are finished?
How will you get the smallest of the next item in each list?
The code I have written above is called pseudocode; it is a way of describing the steps of an algorithm. Keep expanding each step until you have pseudocode that you can implement in your chosen language, in this case Java.
Hope that helps ...
I guess your problem is because of possible uneven size of two lists. Try putting while condition as below:
Integer object1 = intObject1.removeFromBack();
Integer object2 = intObject2.removeFromBack();
while(object1 != null || object2!= null){
if(object1 ==null){
//safe to assume object2 is not null as both not null together (that is the termination condition)
combinedList.insertAtFront(object2);
}else if(object2 ==null){
//safe to assume object1 is not null as both not null together (that is the termination condition)
combinedList.insertAtFront(object1);
}else{
//put you normal condition of handling object1 and object2 being not null
if (object1.intValue() > object2.removeFromBack()) {
combinedList.insertAtFront(object2);
intObject1.insertAtBack(object1);
}
else if (object2.intValue() < object1.intValue()) {
combinedList.insertAtFront(object1);
intObject2.insertAtBack(object2);
}
else if (object1.intValue() == object2.intValue()) {
combinedList.insertAtFront(object1);
}
}
object1 = null;
object2 = null;
try{
object1 = intObject1.removeFromBack();
}catch (EmptyListException emptyListException) {
//do nothing
} // end catch
try{
object2 = intObject2.removeFromBack();
}catch (EmptyListException emptyListException) {
//do nothing
} // end catch
}
Also please note: There are better way of doing the merge of two sorted list elements. This approach is advised in light of your little known custom List class.