InventoryItem.java uses unchecked or unsafe operations - java

I'm learning about comparable and am implementing it in my Inventory class. However when I go to compile the code, the compiler gives an error.
InventoryItem.java uses unchecked or unsafe operations.
Can anyone please help me out. What is wrong with my code and what can I do to fix this issue. Thank you for your help in advance.
class InventoryItem implements Comparable<InventoryItem>
{
private String name;
private int uniqueItemID;
public InventoryItem()
{
name = " ";
uniqueItemID = 0;
}
public InventoryItem(String newName, int newItemID)
{
name = newName;
uniqueItemID = newItemID;
}
public InventoryItem(InventoryItem i)
{
name = i.name;
uniqueItemID = i.uniqueItemID;
}
public void setName(String newName)
{
name = newName;
}
public void setItemID(int newItemID)
{
uniqueItemID = newItemID;
}
public int getItemID()
{
return uniqueItemID;
}
public String getName()
{
return name;
}
public int compareTo(InventoryItem i)
{
int anotherUniqueID = i.getItemID();
return (this.uniqueItemID - anotherUniqueID);
}
public static void sort(Comparable[] a, int numberUsed)
{
int index, indexOfNextSmallest;
for(index = 0; index < numberUsed - 1; index++)
{
indexOfNextSmallest = indexOfSmallest(index, a, numberUsed);
interchange(index, indexOfNextSmallest, a);
}
}
private static int indexOfSmallest(int startIndex, Comparable[] a, int numberUsed)
{
Comparable min = a[startIndex];
int indexOfMin = startIndex;
int index;
for(index = startIndex + 1; index < numberUsed; index++)
{
if(a[index].compareTo(min) < 0)
{
min = a[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void interchange(int i, int j, Comparable[] a)
{
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public class InventoryItemTester
{
public static void main(String [] args)
{
InventoryItem[] items = new InventoryItem[3];
items[0] = new InventoryItem("Pens", 2);
items[1] = new InventoryItem("Pencils", 3);
items[2] = new InventoryItem("Notebooks", 1);
System.out.println("Before sorting");
System.out.println(items[0]);
System.out.println(items[1]);
System.out.println(items[2]);
InventoryItem.sort(items, items.length);
System.out.println("After sorting");
System.out.println(items[0]);
System.out.println(items[1]);
System.out.println(items[2]);
}
}

At a guess I'd say this line is causing the issue (Your compiler tells you exactly which line is the problem, this might be useful to include in your next question):
private static int indexOfSmallest(int startIndex, Comparable[] a, int numberUsed)
{
Comparable min = a[startIndex];
int indexOfMin = startIndex;
int index;
for(index = startIndex + 1; index < numberUsed; index++)
{
here==========> if(a[index].compareTo(min) < 0)
{
You are calling compareTo with a InventoryItem where it is expecting an Object. You could add a #SuppressWarnings annotation which would make it go away :)
The basic idea of Comparable and Comparator is they apply a sorting order to an Object so that the standard JDK Collections objects can do all the hard work for you.
In your case your comparesTo method does the correct thing, however I'm not sure if this is good planning or good luck, so things to note:
InventoryItem.comparesTo method needs to evaluate the current instance to the provided instance and return an integer signifying the ordering, -1 means the instance (ie this) should be ordered before the argument, 0 means they are the same and 1 means the instance is after the argument. Something like this lets the JDK do all the hard work for you
public int compareTo(InventoryItem i)
{
return Integer.valueOf(this.uniqueItemID).compareTo(i.uniqueItemID);
}
In order to use Comparable all you really need to do is implement it and then use the standard JDK Collections classes to do all the heavy lifting for you, eg:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class InventoryItemTest
{
public static void main(String [] args)
{
List<InventoryItem> items = new ArrayList<InventoryItem>();
items.add(new InventoryItem("Pens", 2));
items.add(new InventoryItem("Pencils", 3));
items.add(new InventoryItem("Notebooks", 1));
System.out.println("Before sorting");
System.out.println(items);
Collections.sort(items);
System.out.println("After sorting");
System.out.println(items);
}
}
I realise this might not be as much fun as writing your own sorting algorithms but if you want to do that with no compiler warnings then you need to start looking at generics

Related

Generic Linear List based on Arrays

I'm trying to write a Linear List based on arrays, but make the list be able to store any value by using Java Generics. This way I can create other programs that utilize it, but pass in different data types. I'm not entirely sure how to do this, any help would be appreciated.
I guess Im struggling trying to set it up and create the functions. The generic type really messes me up.
For example, trying to add a removeFirst() function, I cant use a loop like this:
for (int i = 0; i < n - 1; i++)
newList[i] = newList[i + 1];
— as it says The type of the expression must be an array type but it resolved to ArrayList.
Fair warning, I'm still learning data structures. This is what I have so far:
import java.util.ArrayList;
public class LinearList<T> {
private static int SIZE = 10;
private int n = 0;
private final ArrayList<T> newList = new ArrayList<T>(SIZE);
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public void add(T value, int position) {
newList.add(position, value);
n++;
}
public void addFirst(T value) {
newList.add(0, value);
n++;
}
public void removeLast() {
T value = null;
for (int i = 0; i < newList.size(); i++)
value = newList.get(i);
newList.remove(value);
n--;
}
public void removeFirst() {
newList.remove(0);
n--;
}
public T first() {
return newList.get(0);
}
public T last() {
int value = 0;
for (int i = 0; i < newList.size() - 1; i++)
value++;
return newList.get(value);
}
public int count() {
return n;
}
public boolean isFull() {
return (n >= SIZE);
}
public boolean isEmpty() {
return (n <= 0);
}
//part 4
public void Grow() {
int grow = SIZE / 2;
SIZE = SIZE + grow;
}
public void Shrink() {
int grow = SIZE / 2;
SIZE = SIZE - grow;
}
public String toString() {
String outStr = "" + newList;
return outStr;
}
}
A good start would be to make it non-generic with a class you are comfortable with, such as an Integer.
Once you have it set up, you can then make it generic by adding <T> to the class name, then replacing all references of Integer with T.
public class MyArray{ becomes public class MyArray<T>{
public Integer add(Integer value){ becomes public T add(T value){
See What are Generics in Java? for more help

Set an element in an arraylist of a specific class

In my program I have a pair class:
class Pair {
public int ind = 0;
public String letter = "";
public Pair(int a, String b) {
ind = a; //index
letter = b;
}
}
how do I set the index (ind) of an element in an arraylist of Pairs? I have tried
RightMotor.ind.set(j, i);
and
LeftMotor.set(j, i).ind;
but they don't seem to work.
First you need to 'get' the Pair instance, like:
Pair pair = LeftMotor.get(i);
then you can change its fields:
pair.ind = j;
This can also be done in one line:
LeftMotor.get(i).ind = j;
Hint 1: this is not changing the index (position) of the instance in the list, LeftMotor.get(i) will still return the same element. i and ind are two completely disjunct values.
Hint 2: normally it is better to have private fields and have a method (setter) to change the fields (encapsulation):
class Pair {
private int ind = 0;
private String letter = "";
public Pair(int a, String b) {
ind = a; //index
letter = b;
}
public void setInd(int newInd) {
ind = newInd;
}
}
Hint 3: just to be clear, just because it is called ind it is not the index (position) of the list. It is a whole different question if you want to change the order of the elements in the list.
You want to make those instance variables private, then getters/setters to access/modify them. This allows you to safely and securely manipulate the data with a reduced chance of bleedover (which can crash your program or cause unintended consequences).
Within your class:
class Pair {
private int ind = 0;
private String letter = "";
public Pair(int index, String letter) {
ind = index;
letter = letter;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getLetter() {
return this.letter;
}
public void setLetter(String letter) {
this.letter = letter;
}
public void setIndexAndLetter(int index, String letter) {
this.index = index;
this.letter = letter;
}
}
Elsewhere in your program:
Pair rightMotor = new Pair(1, "a");
Pair leftMotor = new Pair(2, "b");
Pair middleMotor = new Pair(0, "");
rightMotor.setInd(3);
leftMotor.setLetter("d");
middleMotor.setIndAndLetter(rightMotor.getInd() + leftMotor.getInd(), "z");
You have to create a Pair instance using the Pair constructor before adding it to the ArrayList:
RightMotor.add(new Pair(i,j)); // assuming i is an int and j is a String
If you want to replace the Pair stored in a given index use:
RightMotor.set(index,new Pair(i,j));
If you want to change an existing Pair stored in the ArrayList:
RightMotor.get(index).setInd(newValue);
This will require a setter method in your Pair class:
public void setInd (int i) {
ind = i;
}
So I think that you could solve this in a couple of different ways... however I think I know what you are trying to do.... I feel like you are trying to keep the ArrayList and the Pair index synchronized... either way you will need a helper method to accomplish this. I agree with hendripd that you should use private variables and utilize the getters and setters. However this is my solution.
Pair:
public class Pair implements Comparable<Pair> {
private int index = 0;
private String letter = "";
public Pair(int index, String letter) {
this.index = index;
this.letter = letter;
}
public Pair(Pair pair) {
this.index = pair.getIndex();
this.letter = pair.getLetter();
}
#Override
public int compareTo(Pair pair) {
if (this.index > pair.index) {
return 1;
} else if (this.index < pair.index) {
return -1;
} else {
return 0;
}
}
#Override
public String toString() {
return this.index + " " + this.letter;
}
public int getIndex() {
return this.index;
}
public String getLetter() {
return this.letter;
}
public void setIndex(int index) {
this.index = index;
}
public void setLetter(String letter) {
this.letter = letter;
}
}
Main:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static ArrayList<Pair> rightMotor;
public static void main(String[] args) {
rightMotor = new ArrayList<Pair>();
rightMotor.add(new Pair(0, "a"));
rightMotor.add(new Pair(1, "b"));
setIndex(rightMotor, 0, 1);
// If you choose to go with the second option utilizing Comparable<Pair>
// Collections.sort(rightMotor);
for (Pair pair : rightMotor) {
System.out.println(pair.toString());
}
}
public static void setIndex(ArrayList<Pair> motor, int oldIndex, int newIndex) {
Pair tempPair = new Pair(motor.get(oldIndex));
if (oldIndex < newIndex) {
for (int i = oldIndex; i < newIndex; i++) {
motor.set(i, motor.get(i + 1));
motor.get(i).setIndex(i);
}
} else if (oldIndex > newIndex) {
for (int i = oldIndex; i > newIndex; i--) {
motor.set(i, motor.get(i - 1));
motor.get(i).setIndex(i);
}
}
tempPair.setIndex(newIndex);
motor.set(newIndex, tempPair);
}
}
Note that the Pair class implements comparable... you could use Collections.Sort(rightMotor) which then you would only need to fix the indexes of the instances... i.e.
public static void setIndex(ArrayList<Pair> motor, int oldIndex, int newIndex) {
motor.get(oldIndex).setIndex(newIndex);
if (oldIndex < newIndex) {
for (int i = oldIndex; i < newIndex; i++) {
motor.get(i + 1).setIndex(i);
}
} else if (oldIndex > newIndex) {
for (int i = oldIndex; i > newIndex; i--) {
motor.get(i - 1).setIndex(i);
}
}
}
Or... you can use the original one I posted which also handles the sorting at the same time. This keeps your Arraylist in numerical order by index either way.
Test casing:
rightMotor.add(new Pair(0, "a"));
rightMotor.add(new Pair(1, "b"));
rightMotor.add(new Pair(2, "c"));
rightMotor.add(new Pair(3, "d"));
rightMotor.add(new Pair(4, "e"));
rightMotor.add(new Pair(5, "f"));
setIndex(rightMotor, 0, 1);
setIndex(rightMotor, 3, 1);
setIndex(rightMotor, 4, 3);
outputs this result:
0 b
1 d
2 a
3 e
4 c
5 f

Returning Elements From ArrayList Alphabetically

I'm working on a program to manipulate chemical formulae, and I'm writing a method which needs to loop through an ArrayList called "terms" and return the first one alphabetically.
e.g. terms = {Term('H',4),Term('C',2),Term('H',4),Term('C',1)} would return Term('C',2)
I've written this code so far but it's not working. I'm a real beginner to the Java language.
public Term nextElement()
{
int i = 0;
for (i = 0; i < terms.size()-1; i++)
{
int j = 1;
while (i + j <= terms.size())
if (terms.get(i).getElement() > terms.get(i+j).getElement())
{
terms.remove(i+j++);
return terms.get(i);
}
}
return null;
}
I'd appreciate any ideas or suggestions to solve this problem. Thanks!
You have two options here:
Let your Term class implement Comparable interface and override its compareTo() method. Then you can use Collections.sort(listOfTerms) to sort them and loop through.
Add class TermComparator which implements Comparator interface, use Collections.sort(listOfTerms, new TermComparator()) and loops through the sorted list.
1- you can implement Comparable and override compareTo()
int compareTo(Object obj){
Term term = (Term)obj;
if(term.getElement < this.getElement())
return 1;
else if (term.getElement == this.getElement())
return 0;
else
return -1;
}
then use
Collection.sort(terms);
2-
public Term nextElement()
{
char minElement = 'Z';
int index = 0;
for (int i = 0; i < terms.size(); i++)
{
if (terms.get(i).getElement() < minElement)
{
minElement = terms.get(i).getElement();
index = i;
}
}
Term temp = terms.get(index);
terms.remove(index)
return temp;
}
use Collections.sort(terms);it will arrange the list alphabetically.
This is what you need to do:
List<Term> terms = //your list
Collections.sort(terms, new Comparator<Term>() {
#Override
public int compare(Term t1, Term t2) {
return t1.getElement().compareTo(t2.getElement());
}
});
CODE:
public class CodeSample {
public static void main(String[] args) {
List<Term> terms=new ArrayList<Term>();
terms.add(new Term('H',4));
terms.add(new Term('C',2));
terms.add(new Term('H',4));
terms.add(new Term('C',1));
System.out.println("Before Sorting");
for(Term term:terms){
System.out.print(term.toString().concat(" "));
}
Collections.sort(terms,new Comparator<Term>() {
#Override
public int compare(Term object1, Term object2) {
if (object1.getElement() != object2.getElement()) {
return object1.getElement() - object2.getElement();
} else {
return object2.getCount() - object1.getCount();
}
}
});
//Sorted terms
System.out.println("After Sorting");
for(Term term:terms){
System.out.print(term.toString().concat(" "));
}
}
public static class Term{
private char element;
private int count;
public Term(char element, int count) {
super();
this.element = element;
this.count = count;
}
public char getElement() {
return element;
}
public int getCount() {
return count;
}
#Override
public String toString() {
return "Term [element=" + element + ", count=" + count + "]";
}
}
}
OUTPUT:
Before Sorting
Term [element=H, count=4] Term [element=C, count=2] Term [element=H, count=4] Term [element=C, count=1]
After Sorting
Term [element=C, count=2] Term [element=C, count=1] Term [element=H, count=4] Term [element=H, count=4]

What is the most efficient way to simultaneously sort three ArrayLists in Java

I have three ArrayLists. One of Strings - names, and two of Integers - score and picture numbers. I want to sort them simultaneously by the players scores (from highest to lowest). Now i use a simple bubble sort, but i think it will not be efficient when the Lists will be bigger.
This is my code:
public class MyBubbleSort {
public static void bubble_srt(List<Integer> score, List<String> name, List<Integer> pic) {
int n = score.size();
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (score.get(i) < score.get(k)) {
swapNumbers(i, k, score, name, pic);
}
}
printNumbers(score);
}
}
private static void swapNumbers(int i, int j, List<Integer> score, List<String> name, List<Integer> pic) {
int temp;
temp = score.get(i);
score.set(i, score.get(j));
score.set(j, temp);
String s;
s = name.get(i);
name.set(i, name.get(j));
name.set(j, s);
int p;
p = pic.get(i);
pic.set(i, pic.get(j));
pic.set(j, p);
}
private static void printNumbers(List<Integer> input) {
for (int i = 0; i < input.size(); i++) {
System.out.print(input.get(i) + ", ");
}
System.out.print("\n");
}
}
Thanks!
Best way would be to create a class containing score, name and pic properties and have a single List of that class, which you sort using Collections.sort and a Comparator that compares two instances of your class according to the score property.
Bubble sort is in-efficient compared to other sorting algorithms (merge sort, quick sort), and there's no need to implement a sort algorithm yourself, since the standard Java packages already do that for you.
First create a PlayerInfo class as follows:
package test;
public class PlayerInfo {
private String name;
private Integer score;
private Integer pictureId;
public PlayerInfo(final String name, final Integer score, final Integer pictureId) {
this.name = name;
this.score = score;
this.pictureId = pictureId;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public Integer getScore() {
return this.score;
}
public void setScore(final Integer score) {
this.score = score;
}
public Integer getPictureId() {
return this.pictureId;
}
public void setPictureId(final Integer pictureId) {
this.pictureId = pictureId;
}
#Override
public String toString() {
return this.name + ":" + this.score + ":" + this.pictureId;
}
}
Second create a PlayerInfo Comparator. Here we create a ScoreBasedComparator (as per your request, but you can create other comparators as well to fit your specific needs):
package test;
import java.util.Comparator;
public class ScoreBasedComparator implements Comparator<PlayerInfo> {
#Override
public int compare(final PlayerInfo playerInfo1, final PlayerInfo playerInfo2) {
return playerInfo1.getScore().compareTo(playerInfo2.getScore());
}
}
Finally, you can sort your List of PlayerInfo instances, using Collections.sort(<your collection>, <your comparator>) as follows:
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Runner {
public static void main(final String[] args) {
List<PlayerInfo> playerInfos = new ArrayList<PlayerInfo>();
playerInfos.add(new PlayerInfo("A", 123, 1));
playerInfos.add(new PlayerInfo("B", 1, 2));
playerInfos.add(new PlayerInfo("C", 23, 3));
playerInfos.add(new PlayerInfo("D", 300, 4));
Collections.sort(playerInfos, new ScoreBasedComparator());
System.out.println(Arrays.toString(playerInfos.toArray()));
}
}
Running this small program will output the following line:
[B:1:2, C:23:3, A:123:1, D:300:4]
As you can see your collection was unsorted at creation time but is printed sorted by score.
Hope this helps.
If the goal here is to sort three arrays according to one of the arrays, without resorting to combining the arrays into a common class, then a fourth array of indices, 0 to size-1 can be created, then the array of indices is sorted according to one of the arrays (using a built in sort and custom compare). Then all three arrays are reordered according to the array of sorted indices. I don't know if Java has a built in reorder function. C example to reorder 3 arrays, A,B,C according to sorted array of indices I, with time complexity of O(n) (linear, every store places a value in it's ordered position). I is reverted back to 0 to n-1.
// reorder A,B,C in place according to I
// tA,tB,tC are temps
for(i = 0; i < n; i++){
if(i != I[i]){
tA = A[i];
tB = B[i];
tC = C[i];
k = i;
while(i != (j = I[k])){
A[k] = A[j];
B[k] = B[j];
C[k] = C[j];
I[k] = k;
k = j;
}
A[k] = tA;
B[k] = tB;
C[k] = tC;
I[k] = k;
}
}

Sorting algorithms - how to implement my classes in main :)

It's silly problem. I have my own comparator interface, class Student - it's objects will be sorted, class BubbleSort with bubblesorting algorithm and main. I think every class except from main is written quite well, but I have problem with implementation of them in main to make my sorting to start :/ I've just created ArrayList of random Students I want to be sorted, but I have problem with BubbleSort class and have no idea, how to start.
In future (I hope it will be today :)) I will do exactly the same with another classes containing sorting algorithms like BubbleSort here. I think their implementation in main will be identical.
import java.util.Random;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
System.out.println(list);
}
}
.
import java.util.ArrayList;
public class BubbleSort {
private final Comparator comparator;
public BubbleSort(Comparator comparator) {
this.comparator = comparator;
}
public ArrayList<Student> sort(ArrayList<Student> list) {
int size = list.size();
for (int pass = 1; pass < size; ++pass) {
for (int left = 0; left < (size - pass); ++left) {
int right = left + 1;
if (comparator.compare(list.get(left), list.get(right)) > 0)
swap(list, left, right);
}
}
return list;
}
public int compare(Object left, Object right) throws ClassCastException
{ return comparator.compare(left, right); }
private void swap(ArrayList list, int left, int right) {
Object temp = list.get(left);
list.set(left, list.get(right));
list.set(right, temp);
}
}
.
public class Student implements Comparator<Student> {
int rate;
int indeks;
public Student(int ocena, int index) {
this.rate = ocena;
indeks = index;
}
public String toString() {
return "Numer indeksu: " + indeks + " ocena: " + rate + "\n";
}
public int getIndeks() {
return indeks;
}
public int getRate() {
return rate;
}
public int compare(Student left, Student right) {
if (left.getIndeks()<right.getIndeks()) {
return -1;
}
if (left.getIndeks() == right.getIndeks()) {
return 0;
}
else {
return 1;
}
}
}
.
public interface Comparator<T> {
public int compare(T left, T right) throws ClassCastException;
}
Your code looks little bit strange. You didnt mention if you have to use bubble sort so i write both my ideas
1.Without explicitly using bubble sort
You can use Collections.sort() combined with overridencompareTo() method
So your code will look like this
class Student implements Comparable<Student>{
//variables constructor methods go here
private index;
#Override
public int compareTo(Students s) {
int index = s.index;
if (this.index > index) {
return 1;
} else if (this.index == index) {
return 0;
} else {
return -1;
}
}
}
And in your main class Collections.sort(myStudents)
2.Explicitly using bubble sort
Student class
class Student{
//class variables methods constructor goes here
}
Comparator class
class StudentComparator implements Comparator<Student>{
#Override
public int compare(Student a, Student b) {
//bubble sort code goes here
}}
Main class
class MyMainClass{
public static void main(String[] args) {
public int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
Collections.sort(list, new StudentComparator());
}
Two points to make here:
a) You are not calling sort at all. You need to instantiate your BubbleSort class and actually call the method. list = new BubbleSort(new Comparator(){...}).sort(list); <-- This syntax also calls for the sort method to be static so that you don't need to make a new object for every sort. The example below sorts by index.
list = new BubbleSort(new Comparator<Student>() {
#Override
public compare(Student a, Student b) {
return a.getIndeks() - b.getIndeks();
}
}).sort(list);
Btw, this also assumes that BubbleSort is made generic, since it's easier (and kinda makes sense anyway)
b) I hope this is some kind of project where you have to show your ability to make a sorting algorithm, otherwise you should use library methods for these things
Also, while the code is not bad, you might want to show it to someone with professional Java experience (it does not conform to a lot of standards and many things can be improved and made consistent with each other), or post it to https://codereview.stackexchange.com/
I dont see you calling the bubblesort class anywhere. A list will not automatically sort its elements. Please go through this link. You ll find it handy.
http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/

Categories