Currently, I'm working on a generic list in Java. Problem: The prepend method doesn't work the way it should. Instead of adding an element T at index 0 it's creating an endless recursive list.
public class Vector<T>{
private T value;
private Vector<T> next = null;
public Vector(T value){
this.value = value;
}
public Vector(T value, Vector<T> next){
this.value = value;
this.next = next;
}
public void prepend(T element){
this.next = this;
this.value = element;
}
}
public class Main{
...
Vector<Integer> v1 = new Vector<Integer>(new Integer(1));
v1.prepend(new Integer(0));
...
Expected output: {0,1}
Actual output: {0,0,0,0,0,0,0, ........ }
What you are doing: First, you create a Vector with value = 1, next = null. „Prepending“ 0, you set next to this, an endless recursion, then you set value = 0. If you look at your Vector, you first get the value = 0. Then you change to the Vector next, which still is this. Of that „new“ Vector, you output value = 0. Then you change to the Vector next, which still is this. Of that „new“ Vector, you output value = 0. Then ... you get it.
What you most probably want to do: When prepending an Integer, you want to COPY this to next and set value to the new Integer. That would read:
public class Vector<T>{
[…]
public void prepend(T element){
this.next = new Vector<>(value, next); // a Copy Constructor would also be fine
this.value = element;
}
}
this.next = this creates a circular list of a single element.
You are trying to implement the list and a node of the list with the same class. You should use one class to represent the list (and hold a reference to the head of the list), and another class to represent a node of the list.
Your prepend method should create a new link instance. Then that new instance should become the new head of the list and its next should be the original head of the list.
public class Vector<T>{
public static class Node<T> {
private T value;
private Node<T> next = null;
...
}
private Node<T> head;
...
}
Updated :
Your prepend method is wrong. Your method should be like this if you don't want to save the head of the list.
public void prepend(T element){
Vector<T> val = new Vector<T>(element);
val.next = this.next;
this.next = val; // after this statement new Element at inserted at 1 position.
// Swap the values
val.value = this.value;
this.value = element;
}
And in main create a vector
Vector<Integer> v1 = new Vector<Integer>(new Integer(1));
v1.prepend(new Integer(0));
Related
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.
I was trying to delete the first node of Linked List using Node head but it did not work while it works when I used list.head?
import java.util.*;
// Java program to implement
// a Singly Linked List
public class LinkedList {
Node head;
// head of list
// Linked list Node.
// This inner class is made static
// so that main() can access it
static class Node {
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
static void delete(LinkedList list,int x){
Node curr=list.head,prev=list.head;
if(curr.data==x&&curr!=null){
list.head=curr.next;
return ;
}
while(curr.data!=x&&curr.next!=null){
prev=curr;
curr=curr.next;
}
if(curr.data==x)
prev.next=curr.next;
return ;
}
// There is method 'insert' to insert a new node
// Driver code
public static void main(String[] args)
{
/* Start with the empty list. */
LinkedList list = new LinkedList();
list = insert(list, 1);
list = insert(list, 2);
list = insert(list, 3);
list = insert(list, 4);
delete(list,1);
printList(list);
//There is method to print list
}
}
//Output : 2 3 4
When I use code above I am able to delete the first node but when I use this code it does not work
import java.util.*;
// Java program to implement
// a Singly Linked List
public class LinkedList {
Node head;
// head of list
// Linked list Node.
// This inner class is made static
// so that main() can access it
static class Node {
int data;
Node next;
// Constructor
Node(int d)
{
data = d;
next = null;
}
}
static void delete(Node head,int x){
Node curr=head,prev=head;
if(curr.data==x&&curr!=null){
head=curr.next;
return ;
}
while(curr.data!=x&&curr.next!=null){
prev=curr;
curr=curr.next;
}
if(curr.data==x)
prev.next=curr.next;
return ;
}
// There is method 'insert' to insert a new node
// Driver code
public static void main(String[] args)
{
/* Start with the empty list. */
LinkedList list = new LinkedList();
list = insert(list, 1);
list = insert(list, 2);
list = insert(list, 3);
list = insert(list, 4);
delete(list.head,1);
printList(list);
//There is method to print list
}
}
//Output: 1 2 3 4
I was wondering that these are the same thing are different, Node head and list(LinkedList).head
Note: Both method work for other nodes, the difference is only for the first node.
In first one you are passing your list as input and in second one reference to your head node and if you will notice in first example you are modifying your list's head if data is present at first node.Here's the code snippet which is doing this.
Node curr=list.head,prev=list.head;
if(curr.data==x&&curr!=null){
list.head=curr.next;
return ;
}
But in your second example if data is found at first node then your are assigning curr.next to head variable which is local to the method so lists's head value remain unchanged and when you try to print list in main method again it shows old head. Here's the code snippet from second example
Node curr=head,prev=head;
if(curr.data==x&&curr!=null){
head=curr.next;
return ;
}
So if you are storing your head pointer in LinkedList object then you must modify your value in it.
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());
}
}
}
If I have a node with two data variables.
Say
class HuffNode{
public char iData;
public int frequency;
public HuffNode leftChild;
public HuffNode rightChild;
// ---------------------------------------------------------
HuffNode(char d){
this.iData = d;
this.frequency = 0;
}
}
Then, I want to put them in ascending order into a priority que by each Node's frequency.
PriorityQueue<HuffNode> q = new PriorityQueue<HuffNode>();
Set<Character>keys = map.keySet(); //iterator
Iterator<Character> it = keys.iterator();
while(it.hasNext()){
char key = it.next();
HuffNode node = new HuffNode(key);
node.frequency = map.get(key);
q.add()// want to add by frequency
}
If I just add the nodes into the que, I think the nodes will end up in an alphabetical order. How can I change the comparator to the frequency ?
thank you in advance.
Pass a Comparator as a constructor parameter, e.g.
new PriorityQueue<>(
initialCapacity,
new Comparator<HuffNode>() {
#Override public int compare(HuffNode a, HuffNode b) {
return Integer.compare(a.frequency, b.frequency);
}
});
Note that you don't really want the thing you are using to order the nodes to be mutable, especially if it is public - if you were to change the frequency value, it wouldn't automatically reorder in the queue.
You'd be well-served making as many fields as possible final.
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).)