Java: LinkedList [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
is there a way to say that if you reach the null reference, then do something ?
e.g. if i have a linkedlist with just one object and after this comparison, if you reached null then do something...
for(int i = 0; i < queue.size(); i++) {
if (queue.get(i).compareTo(newitem) == -1) {
continue;
}
}
for instance another if-clause in the loop saying
if (queue.equals(null)) {
queue.add(newitem);
}
this is btw the linkedlist
public OrderedQueue() {
queue = new LinkedList<T>(); // generate an empty queue
}

You can always check that the object in your list is null to do a special operation:
for(Element e : queue) {
if(e == null) {
// special operation
} else {
// normal operation
}
}
Also use a for-each loop to iterate over elements.
In your case, using the get(i) method is not very efficient on a LinkedList. Using a for each allows you to abstract the actual type of the Iterable you are iterating over.

Replace everything with:
if (!queue.contains(newItem)) {
queue.add(newItem);
}

Related

What's the meaning of this source code of interface Collection in JAVA? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
In the interface Collection:
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
I am puzzled by the expression:
if (filter.test(each.next())) {
each.remove();
}
Why the "each" is removed when "each.next" match the if condition?
I think the below is more reasonable:
if (filter.test(each)) {
each.remove();
}
What's wrong?
I think your confusion comes from a misunderstanding of the Iterator#remove() method. Here's its documentation:
Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next().
So, it's not each that is being removed from the collection, but the latest element returned by the call to each.next() (but only if filter.test(each.next()) returns true).
Here's some equivalent code but more "spread out" and some small name changes:
default boolean removeIf(Predicate<? super E> shouldRemove) {
Objects.requireNonNull(shouldRemove);
boolean wasModified = false;
Iterator<E> iterator = this.iterator();
while (iterator.hasNext()) {
E currentValue = iterator.next();
if (shouldRemove.test(currentValue)) {
iterator.remove(); // removes 'currentValue' from 'this'
wasModified = true;
}
}
return wasModified;
}
As for why filter.test(each) is wrong, that's because that would result in a compilation error due to mismatched types. The test methods expects an object of type E, but each is an Iterator<E>.

How can I check if an Element in my Lists points to my current element? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm working on a programming exercise, and I stumbled across a problem about "comparing" List objects for a method.
Goal: Check if the previous object in the List is null or if its next attributes points at my current object.
My idea was the following:
public ListElement (String info, ListElement next, ListElement prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public boolean isDeleted() {
ListElement prevElement = getPrev();
ListElement nextElement = getNext();
if(prevElement.next.info.equals(this.info))
return false;
}
However, I'm not sure if I get the correct result / about the approach.
Is there a better way to do this?
Assuming "points to" means "is the exact same instance", you'd have to use == for comparison.
public boolean isDeleted() {
return
// if the previous Object in the List is null
prev == null ||
// if its next attributes points at my current Object
next == this;
}

how to iterate through an object's list? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently facing this problem in Java, lets say I have a class ListOfTasks:
public class ListOfTasks {
private Point startingPoint;
ArrayList<Task> tasks;
}
In another class, I want to iterate through the array list tasks directly by calling ListOfTasks, and not by retrieving tasks first and then iterate through it.
You can do this by implementing Iterable to return the iterator of the array list:
public class ListOfTasks implements Iterable<Task> {
private Point startingPoint;
ArrayList<Task> tasks;
public Iterator<Task> iterator() {
return tasks != null ? tasks.iterator() : Collections.emptyIterator();
}
}
You can then iterate using a for-each
ListOfTasks list = new ListOfTasks();
// add some tasks, etc...
for (Task task : list) {
// use task
}
// or
list.forEach(task -> {
// use task
});
there are many ways to do that:--
Write GETTER/SETTER inside ListOfTasks POJO.
public class ListOfTasks {
private Point startingPoint;
ArrayList<Task> tasks = new ArrayList<>();
GETTER/SETTER
}
then
ListOfTasks list = new ListOfTasks();
for(int i=0 ;i<list.getTask().size();i++){
list.getTasks().get(i);
}
Something like this should work, if I understand your question:
for (int i = 0; i < listOfTasksObject.tasks.size(); i++) {
Task task = listOfTasksObjects.tasks.get(i);
// Now you can work with task...
}
The approach you are taking is wrong, because the responsibility of the property "tasks" is owned by the class ListOfTasks.
So you have to change the approach, and iterate through the set of ListOfTasks instances you have in the other class and call a method, let's say
public Task findTask() {
// do something here to find the Task you were looking for, or return null
}
so the other class should look like this:
List<ListOfTasks> lists = new ArrayList<>();
// populate list here ...
Task found = lists.stream().filter(x => x.findTask()).filter(x => x != null).findAny().orElse(null);
Just dont expose getter for tasks.
create a method in ListOfTasks class like :
public Task get(int index){
return list.get(index);
}
public int size(){
return list.size();
}
now use ListOfTasks like this
for(int i=0 ;i<listOfTasks.size();i++){
// now access Task like this
listOfTasks.get(i);
}

Using the Generic Type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
My Instructor for my Data structures class has told me that there is a better way to implement using a Generic Data type in this method instead of casting everything to E. I am unable to figure out how this better way is implemented or exactly what she means. I know this method I wrote works but if there is a better way I would like to know.
public class GenericSortedArrayBag<E extends Comparable> implements Cloneable,Iterable<E> {
public int numPresents;
public int maxPresents;
private Object[] data;
public void delete(E k) {
boolean found = false;
for(int i=0; i <numPresents; i++) {
if(((E)data[i]).equals(k)) {
found = true;
}
if(found && i<numPresents - 1) {
data[i] = data[i+1];
}
else if(found) {
data[i] = null;
}
}
numPresents--;
}
Instead of
private Object[] data;
you can use
private E[] data;
That way you save the cast
if((data[i]).equals(k))

Refactoring if-else if chain in Java 8 style [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a method with the following if-else-if chain:
if(downstreamActual.getNumber() <= downstreamRecommended.getNumber()){
downstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(upstreamActual.getNumber() <= upstreamRecommended.getNumber()){
upstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(biUpstreamActual.getNumber() <= biUpstreamRecommended.getNumber()){
biUpstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(biDownstreamActual.getNumber() <= biDownstreamRecommended.getNumber()){
biDownstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
Every step we do the same work (call the same method for first object that uses in boolean expression, call showErrorWindow() and throw an Exception)
What are some good techniques especially using Java 8 to make this code more manageable?
Based on your comment, I don't think you need Java 8 constructs.
Just use a method :
public void validate (NumberTextBox actual, NumberTextBox recommended)
{
if(actual.getNumber() <= recommended.getNumber()) {
actual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
}
Then call it 4 times :
validate (downstreamActual,downstreamRecommended);
validate (upstreamActual,upstreamRecommended);
...
Since the first one that fails would throw an exception, thus preventing the rest of them from being tested, you don't need the if else-if structure.
I cannot see the java 8 involvement here, but one thing you could do is create a method for that piece of if-else chain in the following manner:
public void handleStreams() throws NumberFormatException {
if(downstreamActual.getNumber() <= downstreamRecommended.getNumber()) {
setInvalid(downstreamActual);
} else if(upstreamActual.getNumber() <= upstreamRecommended.getNumber()) {
setInvalid(upstreamActual);
} else if(biUpstreamActual.getNumber() <= biUpstreamRecommended.getNumber()) {
setInvalid(biUpstreamActual);
} else if(biDownstreamActual.getNumber() <= biDownstreamRecommended.getNumber()) {
setInvalid(biDownstreamActual);
} else {
return;
}
showErrorWindow();
throw new NumberFormatException();
}
public void setInvalid(MyObject stream) {
stream.setInvalid();
}
If those streams have a common super class then you can implement this directly in them. In other words if
public class DownstreamActual extends CustomStream {
then you can add recommendation as a variable to the CustomStream class
public int recommendedValue;
and set it when you create the instance.. Then you can create a method which will check the values
public void checkRecommendedValue() {
if(this.getNumber() <= this.recommendedValue){
this.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
}
One thing you can do with java 8 is avoid making a separate method (if that calls to you) and create one right inside your method using the new syntax:
BiConsumer<Thing, Thing> check = (actual, recommended) -> {
if (actual.getNumber() <= recommended.getNumber()) {
actual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
};
check.accept(downstreamActual, downstreamRecommended);
check.accept(upstreamActual, upstreamRecommended);
check.accept(biUpstreamActual, biUpstreamRecommended);
check.accept(biDownstreamActual, biDownstreamRecommended);

Categories

Resources