Implementing custom LinkedArrayList with extending AbstractList - java

Problem Definition
I need a collection which has nodes and each node has a constant size partially filled array. Each array may contain different size as long as smaller than previously defined constant size. There will be list of these nodes.
For example :
When an element is needed to be added to the list , list adds an element at the first appropriate node which is not full. If i continuously add(1) , add(2) , add(3) , add(4) , add(1) , list will be demonstrated like this :
Suppose DEFAULT_NODE_CAPACITY = 3
node-0 -> "123"
node-1 -> "41"
When an element is needed to be removed from the list , list removes an element from the first appropriate node which contains and matched with given element. If i remove(1) from the list , list will be demonstrated like this :
node-0 -> "23"
node-1 -> "41"
What did I try ?
I have considered the using inner class which is static one , because node class should not access the fields and methods of outher class. All types must have been generic so I put the generic key value that is identical for each constructor.
Critical point was that I had to use AbstractList class in my custom collection.At this point I really confuse about what structure that i will be use for invocating node class which has partially fixed array.
Questions
How can I override AbstractList methods which conform my node inner class . When I read the Java API Documentation , for creating modifiable i just need to override
get()
set()
remove()
add()
size()
at this point , how can i override all of them efficiently by conforming my problem definition ?
What data type should I use for invocating Node<E> ? and How can implement it ?
How did I implement ?
package edu.gtu.util;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
public class LinkedArrayList<E> extends AbstractList<E>
implements List<E> , Collection<E>, Iterable<E> {
public static final int DEFAULT_CAPACITY = 10;
public static final int CONSTANT_NODE_CAPACITY = 3;
/* Is that wrong ? , how to be conformed to AbstractList ? */
private Node<E>[] listOfNode = null;
/*---------------------------------------------------------*/
private int size;
private static class Node<E> {
private Object[] data;
private Node<E> next = null;
private Node<E> previous = null;
private Node( Object[] data , Node<E> next , Node<E> previous ) {
setData(data);
setNext(next);
setPrevious(previous);
}
private Node( Object[] data ) {
this( data , null , null );
}
private void setData( Object[] data ) {
this.data = data;
}
private void setNext( Node<E> next ) {
this.next = next;
}
private void setPrevious( Node<E> previous ) {
this.previous = previous;
}
private Object[] getData() {
return data;
}
private Node<E> getNext() {
return next;
}
private Node<E> getPrevious() {
return previous;
}
}
private void setSize( int size ) {
this.size = size;
}
public LinkedArrayList() {
super();
}
public LinkedArrayList( int size ) {
super();
setSize( size );
listOfNode = (Node<E>[]) new Object[size()];
}
public LinkedArrayList(Collection<E> collection ) {
super();
}
#Override
public E get( int i ) {
}
#Override
public boolean add(E e) {
return super.add(e);
}
#Override
public boolean remove(Object o) {
return super.remove(o);
}
#Override
public E set(int index, E element) {
return super.set(index, element);
}
#Override
public int size() {
return size;
}
}

First, you need to add a field to Node that tells you how many data items are stored in that node.
Then:
size has to iterate over the nodes and compute the sum of the sizes of the nodes. Or you can maintain a separate size, and update it with every add and remove.
add has to find the node where the item can be inserted. If there's room in that node, just add it there. If that node is full, you have to create a new node.
remove has to find the right node and remove the item from that node. If the node becomes empty, the node itself can be removed.
get has to iterate over the nodes, keeping track of how many items it skips over, until it find the node that must contain the node.
set - same as get, except that it replaces the item in addition to returning it
You'll find better descriptions in wikipedia: https://en.wikipedia.org/wiki/Unrolled_linked_list
This article also suggests an important optimization for add/remove.

Related

How to set a variable with type List<T> to a value with type ArrayList<T> using the constructor

An implementation of a graph node is as follows (I cannot change the implementation as it is from a coding website):
class Node {
public int val;
public List<Node> neighbors;
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
If I pass a node to my copyGraph function below, I wouldn't be able to make a copy of that node by calling the Node constructor because I get
incompatible types: List cannot be converted to ArrayList
class Solution {
public Node copyGraph(Node node) {
Node n = new Node(node.val, node.neighbors);
//do some code
}
}
How else could I make a new Node with this implementation?
Problem
That API is poorly designed, FYI. The constructor should accept a List rather than ArrayList. Ideally that code would be:
public Node ( int _val , List < Node > _neighbors ) { … }
… or perhaps even the more general Collection if order were unimportant.
public Node ( int _val , Collection < Node > _neighbors ) { … }
Workaround
Two ways to work around that poor design: cast, or copy.
If you know for sure that your List object is actually an ArrayList, cast as shown in the correct Answer by coconan.
If you are not sure of the concrete implementation of your List object, construct a new ArrayList while passing your List.
Node n = new Node ( node.val, new ArrayList < Node > ( nodesList ) );
You can cast node.neighbors to ArrayList with (ArrayList<Node>) node.neighbors
class Solution {
public Node copyGraph(Node node) {
Node n = new Node(node.val, (ArrayList<Node>) node.neighbors);
//do some code
}
}

Implement doubly linked list

I've looked around on this forum regarding the implementation of doubly linked lists and I can't a grasp of the below code.
// instance variables of the DoublyLinkedList
private final Node<E> header; // header sentinel
private final Node<E> trailer; // trailer sentinel
private int size = 0; // number of elements in the list
private int modCount = 0; // number of modifications to the list (adds or removes)
/**
* Creates both elements which act as sentinels
*/
public DoublyLinkedList() {
header = new Node<>(null, null, null); // create header
trailer = new Node<>(null, header, null); // trailer is preceded by header
header.setNext(trailer); // header is followed by trailer
}
I've seen videos about linked lists and doubly ones, but I haven't seen this kind of implementation. What's the logic behind, for example: trailer = new Node<>(null, header, null)?
You have Probably some DoubleLinkedList like:
/**
* A double linked list.
*
*/
public class DoubleLinkedList<E> {
private final Node<E> header; // header sentinel
private final Node<E> trailer; // trailer sentinel
private int size = 0; // number of elements in the list
private int modCount = 0; // number of modifications to the list (adds or removes)
public DoubleLinkedList() {
this.header = new Node<>(
// The successor of the header is the trailer.
// It will be set with: header.setNext(trailer);
null,
// The predecessor of the header is always null,
// because there there is no node before the first
null,
// The payload of the node is null.
// I guess it is just a part of the example.
null
);
this.trailer = new Node<>(
// The successor of the trailer is always null,
// because there there is no node after the last
null,
// The predecessor of the trailer is the header
// at construction of this object
header,
// The payload of the node is null.
// I guess it is just a part of the example.
null
);
// Now is the successor of the header set to the trailer.
header.setNext(trailer);
}
// Some list methods like add, remove, get, ...
/**
* The nodes of the List
*
* #param <T> The type of the stored objects in the list.
*/
static class Node<T> {
/**
* The predecessor of this node.
*/
private Node<T> predecessor;
/**
* The successor of this node.
*/
private Node<T> successor;
/**
* The payload
*/
private final T payload;
public Node(final Node<T> successor, final Node<T> predecessor, final T payload) {
this.predecessor = successor;
this.successor = successor;
this.payload = payload;
}
// Getter and Setter:
private Node<T> getPredecessor() {
return this.predecessor;
}
private void setNext(final Node<T> next) {
this.predecessor = next;
}
private Node<T> getSuccessor() {
return this.successor;
}
private void setPrevious(final Node<T> previous) {
this.successor = previous;
}
private T getPayload() {
return this.payload;
}
}
}
This is architectural not very beautiful, but I think this explanation matches your case.
Given a list (of any kind), you need to know at least how to get to the first element, and how to tell when you've seen the last element.
There are a few ways to arrange for these requirements to be satisfied.
For a linked list, to know where the list starts, you might have a simple references to the first node, or you might have a full 'dummy' node that always exists.
To know where the list ends, you might have a null 'next' reference, or you might have a full 'dummy' node that always exists.
The dummy-node approach can often result in cleaner code, because then all actual nodes will always have a 'previous' node, and all actual nodes will always have a 'next' node.
That seems to be the approach being taken in your code extract.

How to sort a list when certain values must appear later than others, potentially ignoring sort order for such items that need 'delaying' [duplicate]

This question already has answers here:
Sample Directed Graph and Topological Sort Code [closed]
(7 answers)
Closed 4 years ago.
Problem
I have the requirement to sort a list by a certain property of each object in that list. This is a standard action supported in most languages.
However, there is additional requirement that certain items may depend on others, and as such, must not appear in the sorted list until items they depend on have appeared first, even if this requires going against the normal sort order. Any such item that is 'blocked', should appear in the list the moment the items 'blocking' it have been added to the output list.
An Example
If I have items:
[{'a',6},{'b',1},{'c',5},{'d',15},{'e',12},{'f',20},{'g',14},{'h',7}]
Sorting these normally by the numeric value will get:
[{'b',1},{'c',5},{'a',6},{'h',7},{'e',12},{'g',14},{'d',15},{'f',20}]
However, if the following constraints are enforced:
a depends on e
g depends on d
c depends on b
Then this result is invalid. Instead, the result should be:
[{'b',1},{'c',5},{'h',7},{'e',12},{'a',6},{'d',15},{'g',14},{'f',20}]
Where b, c, d, e, f and h have been sorted in correct order b, c, h, e, d and f; both a and g got delayed until e and d respectively had been output; and c did not need delaying, as the value it depended on, b, had already been output.
What I have already tried
Initially I investigated if this was possible using basic Java comparators, where the comparator implementation was something like:
private Map<MyObject,Set<MyObject>> dependencies; // parent to set of children
public int compare(MyObj x, MyObj y) {
if (dependencies.get(x).contains(y)) {
return 1;
} else if (dependencies.get(y).contains(x)) {
return -1;
} else if (x.getValue() < y.getValue()) {
return -1;
} else if (x.getValue() > y.getValue()) {
return 1;
} else {
return 0;
}
}
However this breaks the requirement of Java comparators of being transitive. Taken from the java documentation:
((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.
However, in the above example
a(6) < h(7) : true
h(7) < e(12) : true
a(6) < e(12) : false
Instead, I have come up with the below code, which while works, seems massively over-sized and over-complex for what seems like a simple problem. (Note: This is a slightly cut down version of the class. It can also be viewed and run at https://ideone.com/XrhSeA)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public final class ListManager<ValueType extends Comparable<ValueType>> {
private static final class ParentChildrenWrapper<ValueType> {
private final ValueType parent;
private final Set<ValueType> childrenByReference;
public ParentChildrenWrapper(ValueType parent, Set<ValueType> childrenByReference) {
this.parent = parent;
this.childrenByReference = childrenByReference;
}
public ValueType getParent() {
return this.parent;
}
public Set<ValueType> getChildrenByReference() {
return this.childrenByReference;
}
}
private static final class QueuedItem<ValueType> implements Comparable<QueuedItem<ValueType>> {
private final ValueType item;
private final int index;
public QueuedItem(ValueType item, int index) {
this.item = item;
this.index = index;
}
public ValueType getItem() {
return this.item;
}
public int getIndex() {
return this.index;
}
#Override
public int compareTo(QueuedItem<ValueType> other) {
if (this.index < other.index) {
return -1;
} else if (this.index > other.index) {
return 1;
} else {
return 0;
}
}
}
private final Set<ValueType> unsortedItems;
private final Map<ValueType, Set<ValueType>> dependentsOfParents;
public ListManager() {
this.unsortedItems = new HashSet<>();
this.dependentsOfParents = new HashMap<>();
}
public void addItem(ValueType value) {
this.unsortedItems.add(value);
}
public final void registerDependency(ValueType parent, ValueType child) {
if (!this.unsortedItems.contains(parent)) {
throw new IllegalArgumentException("Unrecognized parent");
} else if (!this.unsortedItems.contains(child)) {
throw new IllegalArgumentException("Unrecognized child");
} else if (Objects.equals(parent,child)) {
throw new IllegalArgumentException("Parent and child are the same");
} else {
this.dependentsOfParents.computeIfAbsent(parent, __ -> new HashSet<>()).add(child);
}
}
public List<ValueType> createSortedList() {
// Create a copy of dependentsOfParents where the sets of children can be modified without impacting the original.
// These sets will representing the set of children for each parent that are yet to be dealt with, and such sets will shrink as more items are processed.
Map<ValueType, Set<ValueType>> blockingDependentsOfParents = new HashMap<>(this.dependentsOfParents.size());
for (Map.Entry<ValueType, Set<ValueType>> parentEntry : this.dependentsOfParents.entrySet()) {
Set<ValueType> childrenOfParent = parentEntry.getValue();
if (childrenOfParent != null && !childrenOfParent.isEmpty()) {
blockingDependentsOfParents.put(parentEntry.getKey(), new HashSet<>(childrenOfParent));
}
}
// Compute a list of which children impact which parents, alongside the set of children belonging to each parent.
// This will allow a child to remove itself from all of it's parents' lists of blocking children.
Map<ValueType,List<ParentChildrenWrapper<ValueType>>> childImpacts = new HashMap<>();
for (Map.Entry<ValueType, Set<ValueType>> entry : blockingDependentsOfParents.entrySet()) {
ValueType parent = entry.getKey();
Set<ValueType> childrenForParent = entry.getValue();
ParentChildrenWrapper<ValueType> childrenForParentWrapped = new ParentChildrenWrapper<>(parent,childrenForParent);
for (ValueType child : childrenForParent) {
childImpacts.computeIfAbsent(child, __ -> new LinkedList<>()).add(childrenForParentWrapped);
}
}
// If there are no relationships, the remaining code can be massively optimised.
boolean hasNoRelationships = blockingDependentsOfParents.isEmpty();
// Create a pre-sorted stream of items.
Stream<ValueType> rankedItemStream = this.unsortedItems.stream().sorted();
List<ValueType> outputList;
if (hasNoRelationships) {
// There are no relationships, and as such, the stream is already in a perfectly fine order.
outputList = rankedItemStream.collect(Collectors.toList());
} else {
Iterator<ValueType> rankedIterator = rankedItemStream.iterator();
int queueIndex = 0;
outputList = new ArrayList<>(this.unsortedItems.size());
// A collection of items that have been visited but are blocked by children, stored in map form for easy deletion.
Map<ValueType,QueuedItem<ValueType>> lockedItems = new HashMap<>();
// A list of items that have been freed from their blocking children, but have yet to be processed, ordered by order originally encountered.
PriorityQueue<QueuedItem<ValueType>> freedItems = new PriorityQueue<>();
while (true) {
// Grab the earliest-seen item which was once locked but has now been freed. Otherwise, grab the next unseen item.
ValueType item;
boolean mustBeUnblocked;
QueuedItem<ValueType> queuedItem = freedItems.poll();
if (queuedItem == null) {
if (rankedIterator.hasNext()) {
item = rankedIterator.next();
mustBeUnblocked = false;
} else {
break;
}
} else {
item = queuedItem.getItem();
mustBeUnblocked = true;
}
// See if this item has any children that are blocking it from being added to the output list.
Set<ValueType> childrenWaitingUpon = blockingDependentsOfParents.get(item);
if (childrenWaitingUpon == null || childrenWaitingUpon.isEmpty()) {
// There are no children blocking this item, so start removing it from all blocking lists.
// Get a list of all parents that is item was blocking, if there are any.
List<ParentChildrenWrapper<ValueType>> childImpact = childImpacts.get(item);
if (childImpact != null) {
// Iterate over all those parents
ListIterator<ParentChildrenWrapper<ValueType>> childImpactIterator = childImpact.listIterator();
while (childImpactIterator.hasNext()) {
// Remove this item from that parent's blocking children.
ParentChildrenWrapper<ValueType> wrappedParentImpactedByChild = childImpactIterator.next();
Set<ValueType> childrenOfParentImpactedByChild = wrappedParentImpactedByChild.getChildrenByReference();
childrenOfParentImpactedByChild.remove(item);
// Does this parent no longer have any children blocking it?
if (childrenOfParentImpactedByChild.isEmpty()) {
// Remove it from the children impacts map, to prevent unnecessary processing of a now empty set in future iterations.
childImpactIterator.remove();
// If this parent was locked, mark it as now freed.
QueuedItem<ValueType> freedQueuedItem = lockedItems.remove(wrappedParentImpactedByChild.getParent());
if (freedQueuedItem != null) {
freedItems.add(freedQueuedItem);
}
}
}
// If there are no longer any parents at all being blocked by this child, remove it from the map.
if (childImpact.isEmpty()) {
childImpacts.remove(item);
}
}
outputList.add(item);
} else if (mustBeUnblocked) {
throw new IllegalStateException("Freed item is still blocked. This should not happen.");
} else {
// Mark the item as locked.
lockedItems.put(item,new QueuedItem<>(item,queueIndex++));
}
}
// Check that all items were processed successfully. Given there is only one path that will add an item to to the output list without an exception, we can just compare sizes.
if (outputList.size() != this.unsortedItems.size()) {
throw new IllegalStateException("Could not complete ordering. Are there recursive chains of items?");
}
}
return outputList;
}
}
My question
Is there an already existing algorithm, or an algorithm significantly shorter than the above, that will allow this to be done?
While the language I am developing in is Java, and the code above is in Java, language-independent answers that I could implement in Java are also fine.
This is called topological sorting. You can model "blocking" as edges of a directed graph. This should work if there are no circular "blockings".
I've done this in <100 lines of c# code (with comments). This implementation seems a little complicated.
Here is the outline of the algorithm
Create a priority queue that is keyed by value that you want to sort by
Insert all the items that do not have any "blocking" connections incoming
While there are elements in the queue:
Take an element of the queue. Put it in your resulting list.
If there are any elements that were being directly blocked by this element and were not visited previously, put them into the queue (an element can have more than one blocking element, so you check for that)
A list of unprocessed elements should be empty at the end, or you had a cycle in your dependencies.
This is essentialy Topological sort with built in priority for nodes. Keep in mind that the result can be quite suprising depending on the number of connections in your graph (ex. it's possible to actually get elements that are in reverse order).
As Pratik Deoghare stated in their answer, you can use topological sorting. You can view your "dependencies" as arcs of a Directed Acyclic Graph (DAG). The restriction that the dependencies on the objects are acyclic is important as topological sorting is only possible "if and only if the graph has no directed cycles." The dependencies also of course don't make sense otherwise (i.e. a depends on b and b depends on a doesn't make sense because this is a cyclic dependency).
Once you do topological sorting, the graph can be interpreted as having "layers". To finish the solution, you need to sort within these layers. If there are no dependencies in the objects, this leads to there being just one layer where all the nodes in the DAG are on the same layer and then they are sorted based on their value.
The overall running time is still O(n log n) because topological sorting is O(n) and sorting within the layers is O(n log n). See topological sorting wiki for full running time analysis.
Since you said any language that could be converted to Java, I've done a combination of [what I think is] your algorithm and ghord's in C.
A lot of the code is boilerplate to handle arrays, searches, and array/list insertions that I believe can be reduced by using standard Java primitives. Thus, the amount of actual algorithm code is fairly small.
The algorithm I came up with is:
Given: A raw list of all elements and a dependency list
Copy elements that depend on another element to a "hold" list. Otherwise, copy them to a "sort" list.
Note: an alternative is to only use the sort list and just remove the nodes that depend on another to the hold list.
Sort the "sort" list.
For all elements in the dependency list, find the corresponding nodes in the sort list and the hold list. Insert the hold element into the sort list after the corresponding sort element.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
// sort node definition
typedef struct {
int key;
int val;
} Node;
// dependency definition
typedef struct {
int keybef; // key of node that keyaft depends on
int keyaft; // key of node to insert
} Dep;
// raw list of all nodes
Node rawlist[] = {
{'a',6}, // depends on e
{'b',1},
{'c',5}, // depends on b
{'d',15},
{'e',12},
{'f',20},
{'g',14}, // depends on d
{'h',7}
};
// dependency list
Dep deplist[] = {
{'e','a'},
{'b','c'},
{'d','g'},
{0,0}
};
#define MAXLIST (sizeof(rawlist) / sizeof(rawlist[0]))
// hold list -- all nodes that depend on another
int holdcnt;
Node holdlist[MAXLIST];
// sort list -- all nodes that do _not_ depend on another
int sortcnt;
Node sortlist[MAXLIST];
// prtlist -- print all nodes in a list
void
prtlist(Node *node,int nodecnt,const char *tag)
{
printf("%s:\n",tag);
for (; nodecnt > 0; --nodecnt, ++node)
printf(" %c:%d\n",node->key,node->val);
}
// placenode -- put node into hold list or sort list
void
placenode(Node *node)
{
Dep *dep;
int holdflg;
holdflg = 0;
// decide if node depends on another
for (dep = deplist; dep->keybef != 0; ++dep) {
holdflg = (node->key == dep->keyaft);
if (holdflg)
break;
}
if (holdflg)
holdlist[holdcnt++] = *node;
else
sortlist[sortcnt++] = *node;
}
// sortcmp -- qsort compare function
int
sortcmp(const void *vlhs,const void *vrhs)
{
const Node *lhs = vlhs;
const Node *rhs = vrhs;
int cmpflg;
cmpflg = lhs->val - rhs->val;
return cmpflg;
}
// findnode -- find node in list that matches the given key
Node *
findnode(Node *node,int nodecnt,int key)
{
for (; nodecnt > 0; --nodecnt, ++node) {
if (node->key == key)
break;
}
return node;
}
// insert -- insert hold node into sorted list at correct spot
void
insert(Node *sort,Node *hold)
{
Node prev;
Node next;
int sortidx;
prev = *sort;
*sort = *hold;
++sortcnt;
for (; sort < &sortlist[sortcnt]; ++sort) {
next = *sort;
*sort = prev;
prev = next;
}
}
int
main(void)
{
Node *node;
Node *sort;
Node *hold;
Dep *dep;
prtlist(rawlist,MAXLIST,"RAW");
printf("DEP:\n");
for (dep = deplist; dep->keybef != 0; ++dep)
printf(" %c depends on %c\n",dep->keyaft,dep->keybef);
// place nodes into hold list or sort list
for (node = rawlist; node < &rawlist[MAXLIST]; ++node)
placenode(node);
prtlist(sortlist,sortcnt,"SORT");
prtlist(holdlist,holdcnt,"HOLD");
// sort the "sort" list
qsort(sortlist,sortcnt,sizeof(Node),sortcmp);
prtlist(sortlist,sortcnt,"SORT");
// add nodes from hold list to sort list
for (dep = deplist; dep->keybef != 0; ++dep) {
printf("inserting %c after %c\n",dep->keyaft,dep->keybef);
sort = findnode(sortlist,sortcnt,dep->keybef);
hold = findnode(holdlist,holdcnt,dep->keyaft);
insert(sort,hold);
prtlist(sortlist,sortcnt,"POST");
}
return 0;
}
Here's the program output:
RAW:
a:6
b:1
c:5
d:15
e:12
f:20
g:14
h:7
DEP:
a depends on e
c depends on b
g depends on d
SORT:
b:1
d:15
e:12
f:20
h:7
HOLD:
a:6
c:5
g:14
SORT:
b:1
h:7
e:12
d:15
f:20
inserting a after e
POST:
b:1
h:7
e:12
a:6
d:15
f:20
inserting c after b
POST:
b:1
c:5
h:7
e:12
a:6
d:15
f:20
inserting g after d
POST:
b:1
c:5
h:7
e:12
a:6
d:15
g:14
f:20
I think you are generally on the right track, and the core concept behind your solution is similar to the one I will post below. The general algorithm is as follows:
Create a map that associates each item to the items that depend upon it.
Insert elements with no dependencies into a heap.
Remove the top element from the heap.
Subtract 1 from dependency count of each dependent of the element.
Add any elements with a dependency count of zero to the heap.
Repeat from step 3 until the heap is empty.
For simplicity I have replaced your ValueType with a String, but the same concepts apply.
The BlockedItem class:
import java.util.ArrayList;
import java.util.List;
public class BlockedItem implements Comparable<BlockedItem> {
private String value;
private int index;
private List<BlockedItem> dependentUpon;
private int dependencies;
public BlockedItem(String value, int index){
this.value = value;
this.index = index;
this.dependentUpon = new ArrayList<>();
this.dependencies = 0;
}
public String getValue() {
return value;
}
public List<BlockedItem> getDependentUpon() {
return dependentUpon;
}
public void addDependency(BlockedItem dependentUpon) {
this.dependentUpon.add(dependentUpon);
this.dependencies++;
}
#Override
public int compareTo(BlockedItem other){
return this.index - other.index;
}
public int countDependencies() {
return dependencies;
}
public int subtractDependent(){
return --this.dependencies;
}
#Override
public String toString(){
return "{'" + this.value + "', " + this.index + "}";
}
}
The BlockedItemHeapSort class:
import java.util.*;
public class BlockedItemHeapSort {
//maps all blockedItems to the blockItems which depend on them
private static Map<String, Set<BlockedItem>> generateBlockedMap(List<BlockedItem> unsortedList){
Map<String, Set<BlockedItem>> blockedMap = new HashMap<>();
//initialize a set for each element
unsortedList.stream().forEach(item -> {
Set<BlockedItem> dependents = new HashSet<>();
blockedMap.put(item.getValue(), dependents);
});
//place each element in the sets corresponding to its dependencies
unsortedList.stream().forEach(item -> {
if(item.countDependencies() > 0){
item.getDependentUpon().stream().forEach(dependency -> blockedMap.get(dependency.getValue()).add(item));
}
});
return blockedMap;
}
public static List<BlockedItem> sortBlockedItems(List<BlockedItem> unsortedList){
List<BlockedItem> sorted = new ArrayList<>();
Map<String, Set<BlockedItem>> blockedMap = generateBlockedMap(unsortedList);
PriorityQueue<BlockedItem> itemHeap = new PriorityQueue<>();
//put elements with no dependencies in the heap
unsortedList.stream().forEach(item -> {
if(item.countDependencies() == 0) itemHeap.add(item);
});
while(itemHeap.size() > 0){
//get the top element
BlockedItem item = itemHeap.poll();
sorted.add(item);
//for each element that depends upon item, decrease its dependency count
//if it has a zero dependency count after subtraction, add it to the heap
if(!blockedMap.get(item.getValue()).isEmpty()){
blockedMap.get(item.getValue()).stream().forEach(dependent -> {
if(dependent.subtractDependent() == 0) itemHeap.add(dependent);
});
}
}
return sorted;
}
}
You can modify this to more closely fit your use-case.
Java Code for topological sort:
static List<ValueType> topoSort(List<ValueType> vertices) {
List<ValueType> result = new ArrayList<>();
List<ValueType> todo = new LinkedList<>();
Collections.sort(vertices);
for (ValueType v : vertices){
todo.add(v);
}
outer:
while (!todo.isEmpty()) {
for (ValueType r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(r);
// no need to worry about concurrent modification
continue outer;
}
}
}
return result;
}
static boolean hasDependency(ValueType r, List<ValueType> todo) {
for (ValueType c : todo) {
if (r.getDependencies().contains(c))
return true;
}
return false;
}
ValueType is described like below:
class ValueType implements Comparable<ValueType> {
private Integer index;
private String value;
private List<ValueType> dependencies;
public ValueType(int index, String value, ValueType...dependencies){
this.index = index;
this.value = value;
this.dependencies = dependencies==null?null:Arrays.asList(dependencies);
}
public List<ValueType> getDependencies() {
return dependencies;
}
public void setDependencies(List<ValueType> dependencies) {
this.dependencies = dependencies;
}
#Override
public int compareTo(#NotNull ValueType o) {
return this.index.compareTo(o.index);
}
#Override
public String toString() {
return value +"(" + index +")";
}
}
And tested with these values:
public static void main(String[] args) {
//[{'a',6},{'b',1},{'c',5},{'d',15},{'e',12},{'f',20},{'g',14},{'h',7}]
//a depends on e
//g depends on d
//c depends on b
ValueType b = new ValueType(1,"b");
ValueType c = new ValueType(5,"c", b);
ValueType d = new ValueType(15,"d");
ValueType e = new ValueType(12,"e");
ValueType a = new ValueType(6,"a", e);
ValueType f = new ValueType(20,"f");
ValueType g = new ValueType(14,"g", d);
ValueType h = new ValueType(7,"h");
List<ValueType> valueTypes = Arrays.asList(a,b,c,d,e,f,g,h);
List<ValueType> r = topoSort(valueTypes);
for(ValueType v: r){
System.out.println(v);
}
}

How to iterate through ArrayList of objects?

I have a class called SparseMatrix. It contains an ArrayList of Nodes (also class). I am wondering of how to iterate through the Array and access a value in Node. I have tried the following:
//Assume that the member variables in SparseMatrix and Node are fully defined.
class SparseMatrix {
ArrayList filled_data_ = new ArrayList();
//Constructor, setter (both work)
// The problem is that I seem to not be allowed to use the operator[] on
// this type of array.
int get (int row, int column) {
for (int i = 0; i < filled_data_.size(); i++){
if (row * max_row + column == filled_data[i].getLocation()) {
return filled_data[i].getSize();
}
}
return defualt_value_;
}
}
I will probably switch to static arrays (and remake it every time I add an object). If anyone has a solution, I would very much appreciate you sharing it with me. Also, thank you in advance for helping me.
Feel free to ask questions if you don't understand anything here.
Assuming filled_data_ is a list that contains list of objects of a class named Node.
List<Nodes> filled_data_ = new ArrayList<>();
for (Node data : filled_data_) {
data.getVariable1();
data.getVariable2();
}
More info http://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/
First of all, you should not use raw types. See this link for more info: What is a raw type and why shouldn't we use it?
The fix is to declare the type of object held by your array list. Change the declaration to:
ArrayList<Node> filled_data_ = new ArrayList<>();
Then you can access each element in the array list using filled_data_.get(i) (as opposed to filled_data_[i], which would work for a regular array).
`filled_data_.get(i)`
The above will return the element at index i. Documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int)
If you didn't use generic, then you need to cast the object
//Assume that the member variables in SparseMatrix and Node are fully defined.
class SparseMatrix {
ArrayList filled_data_ = new ArrayList();
//Constructor, setter (both work)
// The problem is that I seem to not be allowed to use the operator[] on
// this type of array.
int get (int row, int column) {
for (int i = 0; i < filled_data_.size(); i++){
Node node = (Node)filled_data.get(i);
if (row * max_row + column == node.getLocation()) {
return node.getSize();
}
}
return defualt_value_;
}
}
If array list contains Nodes which defines getLocation() you could use :
((Nodes)filled_data_.get(i)).getLocation()
You could also define
ArrayList<Nodes> filled_data_ = new ArrayList<Nodes>();
When you create the ArrayList object, you should specify the type of the contained elements with <> brackets. It is also good to keep the reference to the List interface - not ArrayList class. To iterate through such a collection, use foreach loop:
Here is an example of the Node class:
public class Node {
private int value;
public Node(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Here is an example of the Main class:
public class Main {
public static void main(String[] args) {
List<Node> filledData = new ArrayList<Node>();
filledData.add(new Node(1));
filledData.add(new Node(2));
filledData.add(new Node(3));
for (Node n : filledData) {
System.out.println(n.getValue());
}
}
}

Java tree structure with multiple children (sorted) at each level

I'm working with a flat List of objects, which nevertheless are associated with each other in parent-child relationships. An object may have any number of children, or none at all. I need to display these objects as a tree, showing those relationships. Each level of the tree should be sorted (the objects are compatible with Collections.sort() ).
The question is two-part:
Does Java have a good out-of-the-box data structure for holding such a tree, or do I need to write one from scratch? (not a huge task, but there's no sense in reinventing the wheel) I know about DefaultTreeModel in Swing... but this application is running on the server-side, and use of the Swing package will get frowned upon in code review.
What would be the best pattern for loading a flat List into such a data-structure? My first thought is to identify the root-level objects, and then use a recursive method to traverse down through their children, grandchildren, etc. However, for the requirement of sorting the peers at each level in the tree... I'm not sure if it makes more sense to worry about this when I'm building the tree, or worry about it later when I'm parsing the tree for display.
Here is a quick-and-dirty Tree implementation that uses TreeSets on all levels (you can supply a comparator, or natural ordering will be used):
public class Tree<T> {
private final Node<T> rootElement;
public void visitNodes(final NodeVisitor<T> visitor){
doVisit(rootElement, visitor);
}
private static <T> boolean doVisit(final Node<T> node,
final NodeVisitor<T> visitor){
boolean result = visitor.visit(node);
if(result){
for(final Node<T> subNode : node.children){
if(!doVisit(subNode, visitor)){
result = false;
break;
}
}
}
return result;
}
public interface NodeVisitor<T> {
boolean visit(Node<T> node);
}
public Node<T> getRootElement(){
return rootElement;
}
private static final class NodeComparator<T> implements Comparator<Node<T>>{
private final Comparator<T> wrapped;
#Override
public int compare(final Node<T> o1, final Node<T> o2){
return wrapped.compare(o1.value, o2.value);
}
public NodeComparator(final Comparator<T> wrappedComparator){
this.wrapped = wrappedComparator;
}
}
public static class Node<T> {
private final SortedSet<Node<T>> children;
private final Node<T> parent;
private T value;
private final Comparator<?> comparator;
#SuppressWarnings("unchecked")
Node(final T value, final Node<T> parent, final Comparator<?> comparator){
this.value = value;
this.parent = parent;
this.comparator = comparator;
children =
new TreeSet<Node<T>>(new NodeComparator<T>((Comparator<T>) comparator));
}
public List<Node<T>> getChildren(){
return new ArrayList<Node<T>>(children);
}
public Node<T> getParent(){
return parent;
}
public T getValue(){
return value;
}
public void setValue(final T value){
this.value = value;
}
public Node<T> addChild(final T value){
final Node<T> node = new Node<T>(value, this, comparator);
return children.add(node) ? node : null;
}
}
#SuppressWarnings("rawtypes")
private static final Comparator NATURAL_ORDER = new Comparator(){
#SuppressWarnings("unchecked")
#Override
public int compare(final Object o1, final Object o2){
return ((Comparable) o1).compareTo(o2);
}
};
private final Comparator<?> comparator;
public Tree(){
this(null, null);
}
public Tree(final Comparator<? super T> comparator){
this(comparator, null);
}
public Tree(final Comparator<? super T> comparator, final T rootValue){
this.comparator = comparator == null ? NATURAL_ORDER : comparator;
this.rootElement = new Node<T>(rootValue, null, this.comparator);
}
public Tree(final T rootValue){
this(null, rootValue);
}
}
Here is some sample code against it:
final Tree<Integer> tree = new Tree<Integer>();
final Node<Integer> rootNode = tree.getRootElement();
rootNode.setValue(1);
final Node<Integer> childNode = rootNode.addChild(2);
final Node<Integer> newChildNode = rootNode.addChild(3);
newChildNode.addChild(4);
tree.visitNodes(new NodeVisitor<Integer>(){
#Override
public boolean visit(final Node<Integer> node){
final StringBuilder sb = new StringBuilder();
Node<Integer> curr = node;
do{
if(sb.length() > 0){
sb.insert(0, " > ");
}
sb.insert(0, String.valueOf(curr.getValue()));
curr = curr.getParent();
} while(curr != null);
System.out.println(sb);
return true;
}
});
Output:
1
1 > 2
1 > 3
1 > 3 > 4
What would be the best pattern for loading a flat List into such a data-structure? My first thought is to identify the root-level objects, and then use a recursive method to traverse down through their children, grandchildren, etc.
If I understand correctly, you only have a flat list, without any concrete associations between its elements, and you can detect somehow whether a particular element is the child of another.
In this case, you could
sort the list
(identify the root node, if it is not known yet)
put the root into a queue
take the first node from the queue
starting from the first element of the list, check each element whether it is a child of the current node; if so, add it to the current level of the tree and put it into the queue
repeat from step 4.
If detecting parent-child relationship is costly, you could improve performance by storing a flag for / nulling out each node whose location within the tree is already identified, so that you can jump over them when traversing the list. Alternatively, you may copy the whole sorted list into a linked list so that it is trivial to remove processed elements from it.
There are no tree structures in Java, but there are sorted ones: TreeSet and TreeMap. See for some hints java data-structure to simulate a data tree
The approach you came up with is what I would do.
How to go about building the tree really depends on what information you have in the initial List.
If each node contains a reference to its parent and a collection of its children, you don't need to build anything other than the root set.
If each node only has a reference to its parent, you do need to build a tree; but you can do it in a single pass over the data using a HashMap to map each node to a list (which you build) of its children.
If the nodes don't even contain a reference to their parents, you'll have to do what Péter suggests.
In any case, I wouldn't bother sorting the whole List first. Sorting a large List will be slower than sorting lots of little ones with the same total length. (This follows from sorting being O(n log n).)

Categories

Resources