Java add Tree to ArrayList - java

Im trying to add each node of a Binary Search Tree to an ArrayList in order, I currently have this code...
private ArrayList<String> toArray(TreeNode<Comparable> root)
{
ArrayList<String> array = new ArrayList<String>();
if(root!= null)
return null;
inorder(root.getLeft());
array.add(root.getValue());
inorder(root.getRight());
return array;
}
but i get this error from running it...
Error: BSTree.java:64: cannot find symbol
symbol : method add(java.lang.Comparable)
location: class java.util.ArrayList<java.lang.String>
thank you for any help.

Would the following Generic method work for you? I'm away from my compiler but solution should be something like this:
private <T extends Comparable<T>> ArrayList<T> toArray(TreeNode<T> root)
{
if(null == root)
return null;
ArrayList<T> array = new ArrayList<T>();
inorder(root.getLeft());
array.add(root.getValue());
inorder(root.getRight());
return array;
}
This TreeNode seems similar to the class in this webpage:
Some CS Class notes

I have used something like this
private void inorder(Node u){
if( tree.isLeaf(u) ){
arrayList.add(u);
}else{
Node v = tree.getLeft(u);
invorder(v);
arrayList.add(u);
v = tree.getRight(v);
invorder(v);
}

Related

How LinkedList object output the content using Syso? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
I have written a small piece of code to implement a linked list data structure. I have an internal class "Node" that has two fields Node and value. Constructor of Linked list accept int value parameter and assign that value to the Node object and add the Node object to the LinkedList object.
My question is which code of java.util.LinkedList makes the list object to be printed as a list of number but not the address of its object?
As When i print "list1", the output is [3,4].
When I print "list", the output is hashcode of the object address.
I didn't find the toString() in java.util.LinkedList class.
How can I make my code to print the content of LinkedList?
Below is the code:
class LinkedList {
Node first;
Node getNode(){
return new Node();
}
class Node{
Node next;
int value;
}
void add(int value){
Node n=this.getNode();
n.value=value;
n.next=null;
if (first==null){
first=n;
} else{
first.next=n;
}
}
}
public class LinkedListTest{
public static void main(String[] args) {
LinkedList list=new LinkedList();
java.util.LinkedList<Integer> list1=new java.util.LinkedList<>();
list1.add(3);
list1.add(4);
list.add(1);
list.add(2);
System.out.println(list);
System.out.println(list1);
}
}
Your class LinkedList (I suggest you rename it since it might be confused with java.util.LinkedList) needs to override the method Object::toString, which is called within printing out to a console.
I didn't find the toString() in java.util.LinkedList class.
A bit detective job - you have to click through the source codes of LinkedList<E> which extends AbstractSequentialList<E> which extends AbstractList<E> which finally extends AbstractCollection<E> (source code) class where is overridden Object::toString method responsible for the String-alike representation of all the element. There you can get inspired.
How can I make my code to print the content of LinkedList?
This way:
#Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
if (first != null) {
Node temp = first;
String sep = "";
while (temp != null) {
sb.append(sep).append(temp.value);
temp = temp.next;
sep = ", ";
}
}
return sb.append(']').toString();
}
You have to create your own toString method for example
class LinkedList {
//...
#Override
public String toString() {
StringBuilder text = new StringBuilder("[");
String del = "";
if (first != null) {
do {
text.append(del).append(first.value);
first = first.next;
del = ", ";
} while (first != null);
}
text.append(']');
return text.toString();
}
}
If you run your code again, the Outputs
[1, 2]

Sorting custom List Java

I have a custom generic linked list class called SLL. For the purpose of my program SLL is going to hold Word objects. In my Word class I have implemented the comparable interface, and defined three comparators. When I go to compile I get an error when trying to sort the custom list, using Collections.sort(). I cannot for the life of me figure out why. I have included some code below. The error message states:
//There is no suitable method found for sort(SLL<Word>, java.util.Comparator<Word>)
private static SLL<Word> wordList = new SLL<Word>();
//methods to populate custom generic list
private void printDescending ()
{
Collections.sort(wordList, Word.frequencyComp1);
System.out.println("10 Most Frequent");
printer(false);
}
My class declaration for SLL and a couple methods are as follows:
public class SLL <T extends Comparable <T>>
{
private Node<T> head , tail;
private int currentSize;
public SLL ()
{
this.head = null;
this.tail = null;
this.currentSize = 0;
}
public void add (Node<T> entry)
{
if (head == null)
{
Node<T> temp = entry;
head = temp;
tail = temp;
currentSize++;
}
else
{
Node<T> temp = entry;
tail.setNext(temp);
tail = temp;
currentSize++;
}
}
Any and all help would be greatly appreciated, I am on the last phase of my program :(
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List)
According to this, your list(SLL) must have a List interface.
private static SLL<Word> wordList = new SLL<Word>();
As per your code SLL is class and wordList is class object with the reference of word class.
If you want use the sort method of Collection class the wordList object must be collection type object like below:
List<SLL<Word>> wordList = new ArrayList<SLL<Word>>();

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());
}
}
}

Casting List<String> to a String return type

The method (below) is a List<String> type and the class that I'm using as a parameter is a String. I was wondering if the way I'm casting would work:
return (List<String>) subList;
This is the method:
public List<String> getWords(String phrase) {
LetterCounter subList = new LetterCounter(phrase);
if (phrase == null) throw new IllegalArgumentException();
for (String element : dict) {
if (subList.contains(element))
subList.add(element);
}
return (List<String>) subList;
}// End of getWords
This URL points to the LetterCounter class:
http://pastebin.com/XbeUSvPx
I put it in paste bin because the class is too long.
Better creating new instance of List<String> and adding String element to that like,
public List<String> getWords(String phrase) {
LetterCounter subList = new LetterCounter(phrase);
if (phrase == null) throw new IllegalArgumentException();
List<String> str = new List<>();
for (String element : dict) {
if (subList.contains(element))
str.add(element);
}
return str;
}
I'm suggesting this, because Your element in loop is String.
If the definition of LetterCounter class is as follows:
public class LetterCounter extends ArrayList<String>{
// implementation
}
You do not need to cast at all. This is because Java allows covariant return type. Please look at What is a covariant return type?

Java - Sorting Grouped by Ties

I'm writing a Java program in which I want to sort a set of items and get the N-highest elements of the set. The thing is, though, that I want the elements to be returned grouped by their rank -- so if I want the 3 highest elements, but there is a tie between two elements for third place, then the third result is a collection that contains the two tied elements.
I know I could write this myself, but I'm wondering if it's already been implemented somewhere else. Does anybody know of anything like this?
Sounds like the Google Collection's MultiMap might be what you're after.
Use the "rank" as your key when inserting your elements. Then sort the keys.
This is what I ended up going with:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.common.collect.Ordering;
public final class Sorting {
private Sorting() {}
public static <T extends Comparable<? super T>> List<List<T>> rank(
Iterable<T> iterable, int nRanks) {
if (nRanks < 0) {
throw new IllegalArgumentException(Integer.toString(nRanks));
}
if (nRanks == 0) {
return new ArrayList<List<T>>();
}
Iterator<T> iter = Ordering.natural().sortedCopy(iterable).iterator();
List<List<T>> ret = new ArrayList<List<T>>();
if (iter.hasNext()) {
T prev = iter.next();
List<T> group = new ArrayList<T>();
group.add(prev);
ret.add(group);
int rank = 1;
while (iter.hasNext()) {
T next = iter.next();
if (prev.compareTo(next) > 0) {
rank++;
if (rank > nRanks) {
break;
}
group = new ArrayList<T>();
ret.add(group);
}
group.add(next);
prev = next;
}
}
return ret;
}
}

Categories

Resources