I had to write a program to do LZWDecode and I decided to use LinkedList to write the LZWDecode program below but I want to convert it to an ArrayList. Anyone have idea on how I can convert the LinkedList to an ArrayList to make it simpler.
Thanks.
import java.util.*;
public class LZWDecoder {
private final int CLEAR_TABLE=256;
private final int END_OF_DATA=257;
private final int TABLE_SIZE=4096;
private static LinkedList<Integer> input = new LinkedList<Integer>();
#SuppressWarnings("unchecked")
private LinkedList<Integer>[] table
= new LinkedList[TABLE_SIZE];
private LinkedList<Integer> temp = new LinkedList<Integer>();
private int index = 258;
private LinkedList<String> trace = new LinkedList<String>();
private boolean view = true;
private void enterData() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the Input Code (EOD = 257):");
int n=0;
while(n!=END_OF_DATA && scan.hasNextInt()){
n = scan.nextInt();
//System.out.println("Adding "+n);
input.add(n);
}
System.out.println("Decoding...\nOutput:");
String code="";
for(int i=0; i<input.size(); i++) {
code+=input.get(i)+" ";
}
trace.add("\nInput: "+code);
//test
/*
while(!input.isEmpty()) {
System.out.println(input.remove());
}
*/
}
private void reset() {
trace.add("Clearing...");
//table.clear();
for(int i=0; i<TABLE_SIZE;i++) {
table[i] = new LinkedList<Integer>();
}
}
private void decode(int c) {
switch(c) {
case CLEAR_TABLE:
trace.add("decode\t"+CLEAR_TABLE+"->[256]");
reset();
break;
case END_OF_DATA:
trace.add("decode\t"+END_OF_DATA+"->[257]");
trace.add("Decoding finished.");
break;
default:
if(c<256) {
trace.add("decode\t"+c+"->["+c+"]");
if(!temp.isEmpty()) append(c);
emit(c);
add(temp);
} else {
trace.add("decode\t"+c+"->["+printTableNode(table[c])+"]");
if(!temp.isEmpty()) append(table[c].get(0));
emit(c, table[c]);
add(temp);
}
}
}
private void emit(int n, LinkedList<Integer> c) {
//int [] a=new int[c.size()];
temp=new LinkedList<Integer>();
for(int i=0; i<c.size(); i++) {
//a[i]=c.get(i);
System.out.print(c.get(i)+" ");
temp.add(c.get(i));
}
trace.add("emit\t"+n+"->"+"["+printTableNode(c)+"]");
}
private void emit(int c) {
//print out output
temp=new LinkedList<Integer>();
temp.add(c);
trace.add("emit\t"+c+"->"+"["+c+"]");
System.out.print(c+" ");
}
/*
private void add(int c) {
//added to table is copied to temp
table[index].add(c);
temp = (LinkedList)table[index].clone();
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
*/
private void add(LinkedList<Integer> c) {
for(int i=0; i<c.size();i++) {
//temp.add(c.get(i));
table[index].add(c.get(i));
}
trace.add("add\t"+index+"->["+printTableNode(table[index])+"]");
}
private void append(int c) {
//table[c].add(12);//add what?
//temp.add(c);
table[index].add(c);
trace.add("append\t"+index+"->["+printTableNode(table[index])+"]");
index++;
}
private String printTableNode(LinkedList l) {
String list="";
for(int i=0; i<l.size();i++) {
list+=l.get(i);
if(i<l.size()-1) {
list+=", ";
}
}
return list;
}
private void printTrace() {
System.out.print("Printing Trace...");
for(int i=0; i<trace.size(); i++) {
System.out.println(trace.get(i));
}
}
public static void main(String[] args) {
// TODO code application logic here
LZWDecoder d = new LZWDecoder();
d.enterData();
while(!input.isEmpty()) {
d.decode(input.remove());
}
System.out.print("\n\n");
d.printTrace();
}
}
LinkedList<String> ll= new LinkedList<String>();
ll.add("A");
ll.add("B");
ll.add("C");
ll.add("D");
List<String> myAL = new ArrayList<String>(ll);
for (Object alObject : myAL)
System.out.println(alObject);
So as you can easily convert the LinkedList to ArrayList bu using its constructor with passing Collection in it.
Hope it will clear your doubt.
Question is not clear enough.
Do you want to use ArrayList instead of Linked List?
Or do you want to convert a Linked List to an ArrayList?
First of all please declare variables on their interface not on implementation,
i.e
LinkedList<Integer>[] table = new LinkedList[TABLE_SIZE];
Instead use
List<Integer>[] table = new LinkedList[TABLE_SIZE];
Please provide a little more details on what you really looking for ....
If you want an array List from another collection, do this,
List<T> t = new ArrayList<>();
t.addAll(linkedList);
Regards
Lyju
Related
This question already has answers here:
this: Cannot use this in static context
(5 answers)
Closed 1 year ago.
I am implementing my own generic Linked List class and it has a instance method called toArray that make a array copy of the linked list and return it. However, whenever I try to call that method on an instance I keep getting error message "SLList.this cannot be referenced from a static context". I searched for it for a bit and some people said that it was because I did not call that method on an instance, but I indeed did.
Here is the class:
public class SLList<ElemType>{
private class StuffNode{
public ElemType item;
public StuffNode next;
public StuffNode(ElemType i, StuffNode n){
item = i;
next = n;
}
}
/** The first item of a list(if it exists) is at sentinel.next*/
private StuffNode sentinel;
private int size;
public ElemType[] toArray(){
ElemType[] arr =(ElemType[]) new Object[this.size];
StuffNode ptr = this.sentinel;
int i = 0;
while(ptr.next != null){
arr[i] = ptr.next.item;
ptr = ptr.next;
i++;
}
return arr;
}
}
It has some method like addLast, addFirst and they have no problem.
public static void main(String[] args){
SLList<Integer> x = new SLList<>(3);
x.addLast(4);
x.addFirst(1);
ElemType[] arr = x.toArray();
}
ElemType[] arr = x.toArray(); is the line where I keep getting error message, and I have used a online Java visualizer to confirm that method works just fine, I just have problem returning the result from it
You could do it like this:
public class Main2 {
public static void main(String[] args) {
SLList<Integer> x = new Main2().new SLList<>(3);
x.addLast(4);
x.addFirst(1);
Integer[] arr = x.toArray();
}
public class SLList<ElemType> {
private class StuffNode {
public ElemType item;
public StuffNode next;
public StuffNode(ElemType i, StuffNode n) {
item = i;
next = n;
}
}
public SLList(ElemType n) {
// Some code for constructor
}
public void addFirst(ElemType n) {
// Some code
}
public void addLast(ElemType n) {
// Some code
}
/**
* The first item of a list(if it exists) is at sentinel.next
*/
private StuffNode sentinel;
private int size;
public ElemType[] toArray() {
ElemType[] arr = (ElemType[]) new Object[this.size];
StuffNode ptr = this.sentinel;
int i = 0;
while (ptr.next != null) {
arr[i] = ptr.next.item;
ptr = ptr.next;
i++;
}
return arr;
}
}
}
or like this:
public class Main2 {
public static void main(String[] args) {
SLList<Integer> x = new SLList<>(3);
x.addLast(4);
x.addFirst(1);
Integer[] arr = x.toArray();
}
// INSERT A STATIC HERE
public static class SLList<ElemType> {
private class StuffNode {
public ElemType item;
public StuffNode next;
public StuffNode(ElemType i, StuffNode n) {
item = i;
next = n;
}
}
public SLList(ElemType n) {
// Some code for constructor
}
public void addFirst(ElemType n) {
// Some code
}
public void addLast(ElemType n) {
// Some code
}
/**
* The first item of a list(if it exists) is at sentinel.next
*/
private StuffNode sentinel;
private int size;
public ElemType[] toArray() {
ElemType[] arr = (ElemType[]) new Object[this.size];
StuffNode ptr = this.sentinel;
int i = 0;
while (ptr.next != null) {
arr[i] = ptr.next.item;
ptr = ptr.next;
i++;
}
return arr;
}
}
}
I have a List<String> and List<Object>. Where, in List<String> I have Strings that I want. In another List<Object>, One of the string variable will have all the Strings that I want. How can I get that String or How can I return true when I found all the listOne Strings.
Example:
List<String> listOne = ["I have"," three"," Dollars"]
List<Object> listTwo = [[1,"I have One Dollar", 500],
[2,"I have two Dollars", 541],
[31,"I have three Dollars with card", 568]
[3,"I have three Dollars", 568],
[4,"I have Four Dollars", 521]]
How I can get Fourth object from listTwo when my listOne Strings exactly matched.
Code Part:
Details.java:
public class Details {
int sNo;
String text;
int value;
public int getsNo() {
return sNo;
}
public void setsNo(int sNo) {
this.sNo = sNo;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
Main Class:
package com.adp.aca.core.helper.daoimpl;
import java.util.ArrayList;
import java.util.List;
import org.apache.velocity.runtime.directive.Foreach;
public class TestClass {
static int count ;
public static void main(String args[]) {
List<String> listOne = new ArrayList<String>();
listOne.add("I have");
listOne.add(" three");
listOne.add(" Dollars");
List<Details> listTwo = new ArrayList<Details>();
Details detailOne = new Details();
detailOne.setsNo(1);
detailOne.setText("I have One Dollar");
detailOne.setValue(500);
Details detailTwo = new Details();
detailTwo.setsNo(2);
detailTwo.setText("I have two Dollars");
detailTwo.setValue(541);
Details detailThree = new Details();
detailThree.setsNo(31);
detailThree.setText("I have three Dollars with card");
detailThree.setValue(568);
Details detailFour = new Details();
detailFour.setsNo(3);
detailFour.setText("I have three Dollars");
detailFour.setValue(568);
Details detailFive = new Details();
detailFive.setsNo(4);
detailFive.setText("I have Four Dollars");
detailFive.setValue(521);
listTwo.add(detailOne);
listTwo.add(detailThree);
listTwo.add(detailFour);
listTwo.add(detailFive);
listTwo.add(detailTwo);
List<String> actualStrings = new ArrayList<String>();
for (Details detail : listTwo) {
actualStrings.add(detail.getText());
}
/** Ended up here ***/
for (int i = 0; i < actualStrings.size(); i++) {
for (int j=0; j<listOne.size();j++) {
actualStrings.get(i).contains(listOne.get(j));
count=i;
}
}
}
}
static String concat(List<String> l) {
StringBuilder sb = new StringBuilder();
for(String s : l)
sb.append(s);
return sb.toString();
}
static Details getMatch(List<Details> listTwo, String s) {
for (Details d : listTwo) {
if (d.getText().equals(s))
return d;
}
return null;
}
You can use the functions like this:
Detail d = getMatch(listTwo, concat(listOne));
you can build a String from List one and compare with Object list in a loop or you can iterate through 2 list and compare as shown in the pseudo code.
for (Details detail: listTwo) {
String text = detail.getText();
String[] texts = text.split(" ");
List textList = Arrays.asList(texts);
if (texts.length == listOne.size()) {
int count = 0;
for (String val: listOne) {
if (textList.contains(val) count++;
else break;
}
if (count == listOne.size()) {
result = detail;
}
}
else {
break;
}
}
package issue;
import java.util.*;
public class Issue {
private static ArrayList<Object> list = new ArrayList<Object>();
public static ArrayList<Object> getArrayStringList(){
for (Object o : list)
System.out.println("["+o+"]");
return list;
}
public static void removeIssue(){
for (int i = 0; i<list.size(); i++){;
System.out.println("["+"["+i+"] "+list.get(i)+"]");
}
Scanner scan = new Scanner(System.in);
System.out.println("Which one would you like to mark as solved?");
int choice = scan.nextInt();
##This is where my problem is ##
Object issue = list.get(choice);
issue
}
public static void addIssue(){
Scanner scan = new Scanner(System.in);
String text= scan.nextLine();
newIssue issue = new newIssue(text);
list.add(issue);
}
}
I want the user input to choose the appropriate element in the ArrayList and then set it to true using the newIssue class. But I can't figure out how to
package issue;
public class newIssue {
public String issueText;
public boolean returned = false;
public newIssue(String issueText){
this.issueText = issueText;
}
public String toString(){
return issueText + returned;
}
}
Try this.
if(list.size() > 0 && choice <= list.size()-1) {
newIssue issue = (newIssue)list.get(choice);
issue.returned = true;
System.out.println("newIssue = "+ issue.toString())
}
Create list as:
private static ArrayList<newIssue> list = new ArrayList<>();
Then you can do:
newIssue issue = list.get(choice);
issue.returned = true;
We're suppose to do tutorial before class but im having trouble with one questions. I have to complete this code:
public class Tester2 {
public static void main(String[] args) {
Employee[] list = new Employee[5];
Employee emp1 = new Employee("Harvey", 75000.00);
Employee emp2 = new Employee("Donna", 10000.00);
Employee emp3 = new Employee("Mike", 40000.00);
addElement(emp1, list);
addElement(emp2, list);
addElement(emp3, list);
insertElementAt(new Employee("Jessica", 100000.00), list, 1);
displayElements(list); // Line 1
removeElementAt(list, 0);
System.out.println("");
displayElements(list); // Line 2
}
public static void displayElements(Employee[] list) {
for (Employee element: list) {
if (element != null) {
System.out.println(element.getName() + " RM " +
element.getSalary());
}
}
}
public static void addElement(Employee emp, Employee[] list) {
for (int i=0; i<list.length; i++) {
if (list[i] == null) {
list[i] = emp;
break;
}
}
}
public static void insertElementAt(Employee emp, Employee[] list,
int pos) {
// Complete the body!
}
public static void removeElementAt(Employee[] list, int pos) {
// Complete the body!
}
}
im not sure what im suppose to put at void insertElementAt. i thought this:
`emp.setname("Jessica");
emp.setEmpCode(100000.00);
list.add(emp);`
but then i saw this line :insertElementAt(new Employee("Jessica", 100000.00), list, 1); and i think theres a different way but i dont know. please help.
You can achieve it by incrementing and decrementing the array based on position of insert and remove in a new array and then copy the array.
Below is the code which worked
public static void insertElementAt(Employee emp, Employee[] list,
int pos) {
Employee[] nlist = new Employee[5];
for (int i=0; i<list.length; i++) {
if(i==pos){
nlist[i]=emp;
}else if(i>pos){
nlist[i]=list[i-1];
}else{
nlist[i]=list[i];
}
}
System.arraycopy(nlist, 0, list, 0, 5);
}
public static void removeElementAt(Employee[] list, int pos) {
Employee[] nlist = new Employee[5];
for (int i=0; i<list.length; i++) {
if(i>=pos){
if(i<4){
nlist[i]=list[i+1];;
}
}else{
nlist[i]=list[i];
}
}
System.arraycopy(nlist, 0, list, 0, 5);
}
In the following code, I instantiated an object of the class and wondering whether I am heading in the right direction or not?. Since it's not a collection, is there a way I can iterate through the items I am inserting using stack class object? Or is there something wrong with the solution design part?
package stack;
import java.util.LinkedList;
import java.util.Queue;
public class StackUsingQPartII {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
public int pop() {
if (q1.peek() == null) {
System.out.println("The stack is empty, nothing to return");
int i = 0;
return i;
} else {
int pop = q1.remove();
return pop;
}
}
public void push(int data) {
if (q1.peek() == null) {
q1.add(data);
} else {
for (int i = q1.size(); i > 0; i--) {
q2.add(q1.remove());
}
q1.add(data);
for (int j = q2.size(); j > 0; j--) {
q1.add(q2.remove());
}
}
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII ();
st.push(2);
}
}
You can make the class enclosing your stack implementation return an iterator() to iterate over the elements in the queue. The iterator() functionality can simply be delegated to the underlying container class holding the stack elements.
public class StackUsingQPartII implements Iterable<Integer>{
#Override
public Iterator<Integer> iterator() {
return q1.iterator();
}
public static void main(String[] args) {
StackUsingQPartII st = new StackUsingQPartII();
st.push(2);
Iterator<Integer> it = st.iterator();
while (it.hasNext()) {
Integer i = it.next();
System.out.println(i);
}
}
}