Sort() "cannot find symbol" - java

Okay i got some issue with the Collection.sort(myintarray); line... it says cannot find symbol trying to make it sort the list so the lowest number in array come first.
package uppgift.pkg1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Arrays;
/**
* #author Fredrik
*
*/
public class Uppgift1 {
public static void main(String[] args) {
//Anrop av metod
skapaArray();
}
public static void skapaArray() {
List<Integer> myintarray = new ArrayList<Integer>();
int ints = 0;
int size = 1;
while (ints < size) {
myintarray.add(ints);
ints++;
}
Collection.sort(myintarray);
System.out.println(myintarray.size());
}
}

You should use Collections:
java.util.Collections;
and:
Collections.sort(myintarray);

It should be
Collections.sort(myintarray);

Sorting a collection in Java is easy, just use the Collections.sort(Collection) to sort your values.
You can do
Collections.sort(myintarray);
instead of
Collection.sort(myintarray);

Related

LinkedList got same value while I printed the list even tough i entered different values

I was running the below code
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
class Ca implements Comparator<CollectionAndClass>{
public int compare(CollectionAndClass a,CollectionAndClass b){
return a.roll-b.roll;
}
}
public class CollectionAndClass {
int roll;
int dar;
public CollectionAndClass(int a,int b) {
roll=a;
dar=b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<CollectionAndClass> link=new LinkedList<CollectionAndClass>();
CollectionAndClass d=new CollectionAndClass(4,5);
link.add(d);
link.add(new CollectionAndClass(5,6));
d.roll=d.dar=1;
link.add(d);
Collections.sort(link, new Ca());
Iterator<CollectionAndClass> itr=link.iterator();
while(itr.hasNext()) {
System.out.println(itr.next().roll);
}
}
}
and i got the output:
1
1
5
I think the output should be 1 4 5 but it is 1 1 5. I don't what's the mistake in my code.
You added d twice to list and you change its roll value to 1
It effects object properties even it d was already added to list before
For expected results add a new instance instead of d:
link.add(new CollectionAndClass(1, 5));
Hey I have modified your code to get the desired output.
package com.dream11.contest;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
class Ca implements Comparator<CollectionAndClass>{
public int compare(CollectionAndClass a,CollectionAndClass b){
return a.roll-b.roll;
}
}
public class CollectionAndClass {
int roll;
int dar;
public CollectionAndClass(int a,int b) {
roll=a;
dar=b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList<CollectionAndClass> link=new LinkedList<CollectionAndClass>();
CollectionAndClass d=new CollectionAndClass(4,5);
link.add(d);
link.add(new CollectionAndClass(5,6));
//d.roll=d.dar=1; You are modifying the same object d, it is reference to object added in list, hence any modification via d will also reflect in the list
// link.add(d); and adding same object again
CollectionAndClass d2=new CollectionAndClass(1,1); // instead create a new object , with new set of values
link.add(d2); // add in the list
Collections.sort(link, new Ca());
Iterator<CollectionAndClass> itr=link.iterator();
while(itr.hasNext()) {
System.out.println(itr.next().roll);
}
}
}
The variable d is basically reference to the object, hence any modification you do using the reference d will modify the same object and the changes will get reflected in the list

Java sorting with comparator [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 8 years ago.
okay look i know this question has been answered time and time again HOWEVER i seriously can't figure out what im doing wrong.
please help.
i have two classes. Machine.java which is the object class and the InventoryTest.java class that holds the main statement.
everywhere i have read says this should work.
this is in the Machine.java class
public static Comparator<Machine> machineIdNumberComparator = new Comparator<Machine>() {
#Override
public int compare(Machine s1, Machine s2) {
String MachineID1 = s1.getMachineIdNumber();
String MachineID2 = s2.getMachineIdNumber();
//ascending order
return MachineID1.compareTo(MachineID2);
}};
this is in the InventoryTest
Collections.sort(arraylist, inventoryArray.machineIdNumberComparator);
this line comes up with problems. arraylist has cannot find symbol error and so does the machineIdNumberComparator.
i need to be able to sort by 3 different methods.
edit: this is how i add and created my arrayList
public List<Machine> inventoryArray = new ArrayList<>();
inventoryArray.add(new Machine(strMachineIdNumber, strManufacturer, strType, dblPowerOrCapacity, dblPrice));
the arraylist is declaired at the start just under the public class where you declair all your variables.
/**
*
* #author stephankranenfeld
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JTextArea;
public class InventoryTest extends JFrame {
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 1500;
private final JTextArea textArea;
private final JButton addMachine;
private final JButton removeMachine;
private final JButton exitButton;
private final JButton sortButton;
final String START_TEXT = String.format("%-20s %-20s %-10s %15s %10s %n", "Machine ID Number:", "Manufacturer:", "Type:", "Power/Capacity:", "Price:"); // starting line of texted used in both display all and entre data buttons.
final String DEVIDER = "-------------------------------------------------------------------------------------\n";// a devider used multple times
public List<Machine> inventoryArray = new ArrayList<>();
/*
junk that isn't needed i think
*/
private void sort() {
JComboBox sortBy = new JComboBox();
sortBy.addItem("ID Number");
sortBy.addItem("Manufacturer");
sortBy.addItem("Type");
int option = JOptionPane.showConfirmDialog(null, sortBy, "Sort by?", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION)
{
//if id is selected sort by id
//if manufacturer is selected sor by manufacturer
//if type is selected sort by type
Collections.sort(inventoryArray, Machine.machineIdNumberComparator);
}
}
}
public class Machine{
/*
* all the get and set methods
*/
public static Comparator<Machine> machineIdNumberComparator = new Comparator<Machine>() {
#Override
public int compare(Machine s1, Machine s2) {
String MachineID1 = s1.getMachineIdNumber();
String MachineID2 = s2.getMachineIdNumber();
//ascending order
return MachineID1.compareTo(MachineID2);
}};
The second argument of Collections.sort() should be Machine.machineIdNumberComparator

mapreduce error:java.lang.indexoutofboundsexception:index:2,size:2

I connect hadoop with the eclipse ,start the job by eclipse plug-in, the mapreduce job can complete successfully,but when i compile my code to jar file and then execute this job by hadoop command,it will throw errors as follows.
Error:java.lang.IndexOutOfBoundsException:Index:1,Size:1
at java.util.ArrayList.rangecheck(Arraylist.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at Combiner.reduce(Combiner.java:32)
at Combiner.reduce(Combiner.java:1)
and my code as follows:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
public class Combiner extends MapReduceBase implements Reducer<Text,Text,Text,Text>{
public void reduce(Text key,Iterator<Text>values,OutputCollector<Text,Text>output,Reporter reporter)
throws IOException{
int num=3;
Comparator<String> comparator=new MyComparator();
PriorityQueue<String> queue=new PriorityQueue<String>(100,comparator);
ArrayList<String> list=new ArrayList<String>();
while(values.hasNext()){
String str=values.next().toString();
queue.add(str);
}
while(!queue.isEmpty()){
list.add(queue.poll());
}
String getCar="";
for(int i=0;i<num;i++){
getCar=getCar+list.get(i)+"\n";
}
output.collect(new Text(""), new Text(getCar));
}
public class MyComparator implements Comparator<String>{
public int compare(String s1,String s2){
if(Long.parseLong(s1.split(",")[4])>Long.parseLong(s2.split(",")[4])){
return 1;
}else if(Long.parseLong(s1.split(",")[4])<Long.parseLong(s2.split(",")[4])){
return -1;
}else{
return 0;
}
}
}
}
This happens, because your list has one element (Size:1), and you ask for the second element (Index:1 - Indexing starts from zero)! A simple System.out.println for each list element will help you get through...
Why do you set the number of elements to 3? If you know that it will be 3 (unlikely), then change the list to an array of size 3. If you don't know that, then change num to list.size(), like:
for(int i=0;i<list.size();i++)
But before anything else, you should understand why you get these values for this key.

Reversing ArrayList<String>

All im trying to do is reverse the ArrayList. Is there a way I could do it through the toString as well or should I just create a method like I did. Im so close, any answers will help! Thanks!
package edu.purse.test;
java.util.ArrayList;
import java.util.Collections;
public class Purse
{
ArrayList<String> coins = new ArrayList<String>();
public Purse()
{
}
public void addCoin(String coinName)
{
coins.add(coinName);
}
public String toString()
{
return "Purse" + coins.toString();
}
public ArrayList<String> getReversed(ArrayList<String> coins)
{
ArrayList<String> copy = new ArrayList<String>(coins);
Collections.reverse(copy);
return copy;
}
}
TESTERCLASS
package edu.purse.test;
import java.util.Collections;
import java.util.List;
public class PurseTester {
public static void main(String[] args) {
Purse p = new Purse();
p.addCoin("Quarter");
p.addCoin("Dime");
p.addCoin("Nickel");
p.addCoin("Penny");
System.out.println(p.toString());
p.getReversed(coins);
}
}
The method
p.getReversed(coins);
returns a reversed list. You can just print it out
System.out.println(p.getReversed(coins));
Note that you are getting a copy of your instance's list, reversing that, and then returning it. If you want to preserve the change, simple call Collections.reverse() on the original, coins.

Java I have an Array that cannot be resolved across a class

I have an Array that is in a class called MusicArray
and I want to be able to print its data and search it in my SearchClass class
import java.util.Arrays;
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
MusicArray ma = new MusicArray();
for(int count = 1; count <= songDetails.length; count++){
System.out.println(SongDetails.length);
System.out.println(songDetails[count - 1]);}
In the MusicArray class I have this
public Music[] getSongDetails() {
return songDetails;
I though that this code snippet made the array availabe to the other classes
What am I missing?
You need to use the ma object to retrieve the array, like this:
Music[] songDetails = ma.getSongDetails();
Then you can iterate over the Music[] array.
You should use ma.getSongDetails() to access the array from your SearchClass.
import java.util.Arrays;
import java.util.Scanner;
public class Searchclass {
public static void main(String[] args) {
MusicArray ma = new MusicArray();
Music [] details = ma.getSongDetails();
for(int count = 0; count < details.length; count++)
{
System.out.println(details.length);
System.out.println(details[count]);
}
}
}
Unfortunately, this code will probably still have problems. You don't add any instances of Music to MusicArray, so either the array will be null (you'll see a NullPointerException) or empty (nothing will print.)

Categories

Resources