Java check empty ArrayList as an class structure - java

I am trying to create class structure as in this example:
public class SubjectListStructure {
public String topic_id;
public String topic_title;
public String created_date;
public String avatar_url;
public String vote;
public String name_family;
}
Now, I want to create an ArrayList consisting of those objects:
ArrayList<SubjectListStructure> nSubjects = = new ArrayList<SubjectListStructure>();
But now I can't check if nSubjects is empty or have some data like with this code:
public static Boolean ContainsAllNulls(ArrayList<SubjectListStructure> arrList)
{
if(arrList != null)
{
for(SubjectListStructure a : arrList)
if(a != null) return false;
}
return true;
}
Or nSubjects.isEmpty() this solution and ContainsAllNulls(nSubjects) could not check correctly and return wrong result

First you should not allow nulls in the list. In this case simply List.isEmpty() will tell you if the list is empty.
If you can't or don't want to disallow nulls, your code works and properly tests if the list only contains nulls.
You don't even have to combine it with the isEmpty() method because the enhanced for works for empty lists and arrays too (in which case the body of the for will not be executed).
You can generalize your code to something like this which works for not just ArrayLists but for all Collections (lists, sets, etc.) and with any element type not just your custom SubjectListStructure type:
public static boolean emptyOrAllNulls(Collection<?> c) {
if (c != null)
for (Object o : c)
if(o != null)
return false;
return true;
}
Note that the enhanced for uses the Collection.iterator() to obtain an Iterator to walk over elements of the collection. In case of empty collections it is more efficient to first check if the collection contains any elements and not go through the iterator:
public static boolean emptyOrAllNulls(Collection<?> c) {
if (c != null && !c.isEmpty())
for (Object o : c)
if(o != null)
return false;
return true;
}

Related

How to test Single Linked List using Assert.assertEquals()

i am trying to test singly linked list using Assert.assertEqual(expected, actual) the linked list has a node index and a value. how can i use Assert.assertEquals() to test it.
This is my code
#Test
void nonEmptyTest() throws ListAccessError {
SingleLinkedList<Integer> list = new SingleLinkedList<Integer>();
SingleLinkedList<Integer> expList = new SingleLinkedList<Integer>();
list.add(0,10);
list.add(1,20);
list.add(2,30);
expList.add(0,10);
expList.add(1,20);
expList.add(2,30);
Assert.assertEquals(expList, list);
}
You need to override boolean equals(Object obj) method for you to expect the assert on the actual values of the list.
Here's a sample on how to override
(Note: I don't know your implementation of SingleLinkedList, you can get an idea from the following code and implement accordingly)
#Override
public boolean equals(Object obj) {
if (obj == null)
return false;
SingleLinkedList<Integer> listToCompare = (SingleLinkedList<Integer>) obj;
SingleLinkedList<Integer> thisList = this;
while (listToCompare != null && thisList != null) {
if (!listToCompare.getData().equals(thisList.getData()))
return false;
listToCompare = listToCompare.getNext();
thisList = thisList.getNext();
}
if (listToCompare == null && thisList == null)
return true;
return false;
}
If you want to compare two different objects to find out whether they're equal, your class that defines those objects generally needs to implement the equals() method. Otherwise Java has no way to know what 'equality' is supposed to mean.
That is, your problem is not in the unit test, it's in the class being tested. The
unit test did its job :-)

Comparing list of objects in Java 8

This post may be duplicate one, apologies for that.
I have worked extensively in Java-6, now moving to Java 8. Is there an efficient way to rewrite the below logic in Java 8?
This compares list of objects with single object, returning true if some object in the list has a matching "Identifier" parameter value.
private boolean compareOrder(UserOrderDTO.OrderConfig givenDeviceConfig, List<UserOrderDTO.OrderConfig> masterConfigList) {
boolean isValidService = false;
for(UserOrderDTO.OrderConfig eachRecord:masterConfigList) {
if(eachRecord.getIdentifier()!=null && givenDeviceConfig.getIdentifier()!=null) {
if(eachRecord.getIdentifier().trim().equalsIgnoreCase(givenDeviceConfig.getIdentifier().trim()) ) {
isValidService = true;
break;
}
}
}
return isValidService;
}
Also if I want to compare two list, any suggestions please
List<UserOrderDTO.OrderConfig> oneList = some value;
List<UserOrderDTO.OrderConfig> twoList = some value;
private boolean compareOrder(UserOrderDTO.OrderConfig givenDeviceConfig, List<UserOrderDTO.OrderConfig> masterConfigList) {
return givenDeviceConfig.getIdentifier() != null
&& masterConfigList.stream().anyMatch(
p -> p.getIdentifier() != null
&& p.getIdentifier().trim().equalsIgnoreCase(givenDeviceConfig.getIdentifier().trim()));
}
.
private static boolean compareOrderLists(List<UserOrderDTO.OrderConfig> list1, List<UserOrderDTO.OrderConfig> list2) {
return list1.stream().anyMatch(
p -> p.getIdentifier() != null
&& list2.stream().anyMatch(
p2 -> p2.getIdentifier() != null
&& p2.getIdentifier().trim().equalsIgnoreCase(p.getIdentifier())));
}
private boolean compareOrder(OrderConfig givenDeviceConfig, List<OrderConfig> masterConfigList) {
//do null and empty checks here
return masterConfigList
.stream()
.anyMatch(o -> o.getIdentifier().equalsIgnoreCase(givenDeviceConfig.getIdentifier()));
}
You can use this for list comparison. If you don't want to include a library, there are plenty of answers on stackoverflow to compare Collections.

Is this Java TreeSet Possible

Consider that I would like to create a class which manages a TreeSet of custom objects with two keys: A String instance identifier, and a long order identifier. The Long value would be used to determine the order of the elements in the list, while the string would be used to determine if two of these elements are duplicates. To clarify, here is what the methods would look like for the custom object
#Override
public boolean equals(Object o) {
if(o == null)
return false;
if(!(o instanceof CustomObject))
return false;
//Determined by string_id values ONLY. Used in TreeSet implementation
CustomObject obj = (CustomObject) o;
return obj.string_id.equals(this.string_id);
}
#Override
public int compareTo(Object another) {
if(another == null || !(another instanceof CustomObject))
return -1;
CustomObject other = (CustomObject) another;
if(other.long_id > this.long_id)
return -1;
else if(other.long_id < this.long_id)
return 1;
else
return 0;
}
Can my TreeSet function this way? I ask, because while testing this, I've found that my implementation only keeps the latest entry, and discards the rest. I'm looking to find out if this is simply an error with my implementation, or if I'm not properly using the TreeSet class and need to refactor my approach.

How to check if Iterator.next() is == null?

How do I check if the next element in the list is null ?
while(it.hasNext()){
System.out.println(it.next()+"\n");
}
this is how I tried, but when the last element is null it prints it as null.
I tried to change it
while(it.hasNext()){
if(it.next()==null){
}else
System.out.println(it.next()+"\n");
}
but this just makes it worst because some of the elements don't even print!
This is my Iteration method/anonymous class
public Iterator<Filmi> iterator3DFilms ()throws FilmiException{
if(filmList.isEmpty())
throw new FilmiException("No Films on the list");
return new Iterator<Filmi>(){
private int index=0;
public boolean hasNext(){
return index <filmList.size();
}
public Filmi next(){
Filmi lb = filmList.get(index++);
if(lb.is3D()== true)
return lb;
if(hasNext())
return next();
return null;
}
public void remove(){}
};
}
The null print only happens at the last element
Thank you.
Naturally, code like
if (it.next() == null){
} else {
System.out.println(it.next()+"\n");
}
will consume every other non-null element, as you are observing. Plus calling it.next() without checking it.hasNext() is a recipe for disaster.
Why not write
Foo/*ToDo - use the correct type here*/ foo = it.next()
if (foo != null){
/*ToDo*/
}
instead?
No it cannot work this way because if it.next() is not null you call it.next() twice which will make you skip a value that could not even be available.
Use a variable instead as next:
Object o = it.next();
if (o != null) {
...
}
you should use stream instead of iterator.
filmList.stream().filter(film->film!=null).filter(film->film.is3D())
Edit:
or, if you'r not in Java 8 :
Predicate<Film> isNotNullAnd3D = new Predicate<Person>() {
public boolean apply(Film f) {
return f != null && f.is3D();
}
};
Collection2.filter(filmList, isNotNullAnd3D)
You never mentioned why you use iterators explicitly in the first place.
Why not use implicit iterator notation like this ? :
for (Film film : filmList) {
if (film != null ){
....
}
}
Additionally to what others said: in case you are doing a for-each loop with a primitive type like int
for (int node : input) {
doSomething(node);
}
you might want to consider using the Wrapper class instead:
for (Integer node : input) {
if (node == null) throw new IllegalArgumentException();
doSomething(node);
}

Homemade Stack Equals method

For my data structures class, we have to create our own Stack data type and the implementation for it as a project. The problem I'm running into is when the professor asked us to implement an equals(Object object) method. Heres what I have so far...
package stack;
import list.*;
public class Stack <E>
implements StackADT<E>//the interface
{
List <E> values;
public Stack()
{
values = new ArrayList<E>();
}
public E push(E value)
{
values.add(value);
return value;
}
public E pop()
{
return values.remove(values.size()-1);
}
public E peek()
{
return values.get(values.size()-1);
}
/** #return true only if this Stack is empty */
public boolean isEmpty()
{
return (values.size()==0);
}
/** Clear this stack, to make it an empty stack */
public void clear()
{
for (int i = 0; i < values.size()-1; i++)
{
pop();
}
}
public String toString()
{
String result = "[";
for (int i = 0; i<values.size(); i++)
{
if (i == values.size()-1)
{
result = result + values.get(i);
}
else
{
result = result + values.get(i) +",";
}
}
result = result + "]";
return result;
}
public boolean equals (Object object)
{
if (!(object instanceof StackADT))
{
return false;
}
StackADT <E> otherStack = new Stack<E>();
for(Object o: object)//heres where i run into trouble
{
otherStack.push(o);
}
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
}
Our Stack is pretty much an ArrayList which we also built in our class. the problem is, I cant add the Object object into a stack because its not something thats iteratable(?able to be iterated over). Is there a better way to do this? I would think a get() would work, since the Stack I create is an ArrayList, but whenever I use get() on otherStack, it can't find the method. I had a temporary solution when I tried casting object as a stack(I hope im using the right terminology). It looked something like this
Stack otherStack = (Stack) object;
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
this seemed to work, but when pop() was called on otherStack, the values in the original list(the one that becomes otherStack) that was passed into the equals() method we're also popped from the original list, leading to an incorrect result. Is there a better way to do this without adding in any other methods? I'm trying to stick as close to the formula set up by my professor as possible, so I dont want to add any extra fields or methods.
any and all help is appreciated
An equals method is not supposed to create anything, not even a temporary object. Rather than creating a new otherStack, cast the object that you have checked to be StackADT, like this:
// This should be the first line of any equals() implementation:
if (object == this) {
return true;
}
// You've got this part right: you need to check the other object's type
if (!(object instanceof StackADT)) {
return false;
}
// Now that you know the type, cast the other object to StackADT<E>
StackADT<E> otherStack = (StackADT<E>)object;
// The next step is to check the sizes:
if (values.size() != otherStack.values.size()) {
return false;
}
// Finally, go through the individual elements in a loop
In the loop that follows, do not pop the other stack. Do not do anything that can modify it. Simply go through the underlying storage (i.e. values), and check elements one by one.
Don't forget to override hashCode as well: you need to do it every time when you override equals for the object to fulfill the contract specified by java.lang.Object.

Categories