Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 days ago.
Improve this question
So I have written this code that works just fine with integers. Now I want to make it generic (extends Number), but keep it an array.
import java.util.Arrays;
public class StudentGrades {
private int grades[];
private int pointer;
private int max_grade;
private int min_grade;
private double average_grade;
private int better_than_average;
private int worse_than_average;
private int excelent_count;
private int good_count;
private int enaught_count;
public int getMax_grade() {
return max_grade;
}
public int getMin_grade() {
return min_grade;
}
public double getAverage_grade() {
return average_grade;
}
public int getBetter_than_average() {
return better_than_average;
}
public int getWorse_than_average() {
return worse_than_average;
}
public int getExcelent_count() {
return excelent_count;
}
public int getGood_count() {
return good_count;
}
public int getEnough_count() {
return enaught_count;
}
StudentGrades()
{
pointer=-1;
grades=new int[1000];
average_grade=0;
better_than_average=0;
worse_than_average=0;
excelent_count=0;
good_count=0;
enaught_count=0;
max_grade=0;
min_grade=0;
}
private void calculate()
{
average_grade=0;
better_than_average=0;
worse_than_average=0;
excelent_count=0;
good_count=0;
enaught_count=0;
max_grade=0;
min_grade=0;
if (pointer<0)return;
double sum=0;
max_grade=grades[0];
min_grade=grades[0];
for (int i=0; i<=pointer;i++)
{
sum+=grades[i];
if(grades[i]>max_grade)
max_grade=grades[i];
if(grades[i]<min_grade)
min_grade=grades[i];
if(grades[i]>=91)
excelent_count++;
else if(grades[i]>=71)
good_count++;
else if (grades[i]>=60)
enaught_count++;
}
average_grade=sum/(double) (pointer+1);
for(int i=0; i<=pointer;i++)
{
if(grades[i]>average_grade)
better_than_average++;
else
worse_than_average++;
}
}
private boolean is_valid(int n)
{
return (n>0 && n<100);
}
public boolean setter( int marks[])
{
for(int i=0; i<marks.length; i++)
{
if(!is_valid(marks[i]))
return false;
}
grades=marks;
pointer=marks.length-1;
calculate();
return true;
}
public boolean adder(int new_element)
{
if(!is_valid(new_element))
return false;
if(grades.length==pointer+1)
{
int[] new_size_array =new int[grades.length*2];
for(int i=0; i<=pointer;i++) new_size_array[i]=grades[i];
grades=new_size_array;
}
pointer++;
grades[pointer]=new_element;
calculate();
return true;
}
public int[] getter()
{
int[] result = new int[pointer+1];
for (int i=0; i<=pointer;i++)
result[i]=grades[i];
return result;
}
public void to_string(){
System.out.println(Arrays.toString(getter()));
}
}
I have done this, but I strongly believe it is completely wrong and Im moving in the wrong direction. Im relatively new to programming, so please make your explanations as detailed as possible. Thamks!
import java.util.Arrays;
import java.lang.reflect.Array;
public class StudentGradesGeneric <E extends Comparable<E>> extends Number{
public StudentGradesGeneric(Class<E> clazz, int capacity) {
grades = (E[]) Array.newInstance(clazz, capacity);
}
private E[] grades;
private int pointer;
private E max_grade;
private E min_grade;
private E average_grade;
private E better_than_average;
private E worse_than_average;
private E excelent_count;
private E good_count;
private E enaught_count;
public E getMax_grade() {
return max_grade;
}
public E getMin_grade() {
return min_grade;
}
public E getAverage_grade() {
return average_grade;
}
public E getBetter_than_average() {
return better_than_average;
}
public E getWorse_than_average() {
return worse_than_average;
}
public E getExcelent_count() {
return excelent_count;
}
public E getGood_count() {
return good_count;
}
public E getEnough_count() {
return enaught_count;
}
StudentGradesGeneric()
{
pointer=-1;
grades= (E[]) new Comparable[1000];
average_grade=null;
better_than_average=null;
worse_than_average=null;
excelent_count=null;
good_count=null;
enaught_count=null;
max_grade=null;
min_grade=null;
}
#Override
public int intValue() {
return 0;
}
#Override
public long longValue() {
return 0;
}
#Override
public float floatValue() {
return 0;
}
#Override
public double doubleValue() {
return 0;
}
private <E> void calculate()
{
average_grade=null;
better_than_average=null;
worse_than_average=null;
excelent_count=null;
good_count=null;
enaught_count=null;
max_grade=null;
min_grade=null;
if (pointer<0)return;
E sum=null;
max_grade=grades[0];
min_grade=grades[0];
for (int i=0; i<=pointer;i++)
{
sum =grades[i] + sum;
if ( grades[i].compareTo(max_grade) > 0)
max_grade=grades[i];
if(grades[i].compareTo(min_grade) < 0)
min_grade=grades[i];
if(grades[i].compareTo(91) >= 0)
excelent_count++;
else if(grades[i]>=71)
good_count++;
else if (grades[i]>=60)
enaught_count++;
}
average_grade=sum/ (pointer+1);
for(int i=0; i<=pointer;i++)
{
if(grades[i]>average_grade)
better_than_average++;
else
worse_than_average++;
}
}
private boolean is_valid(E n)
{
return (n>0 && n<100);
}
public boolean setter( E marks[])
{
for(int i=0; i<marks.length; i++)
{
if(!is_valid(marks[i]))
return false;
}
grades=marks;
pointer=marks.length-1;
calculate();
return true;
}
public boolean adder(E new_element)
{
if(!is_valid(new_element))
return false;
if(grades.length==pointer+1)
{
E[] new_size_array =(E[]) new Comparable[grades.length*2];
for(int i=0; i<=pointer;i++)
new_size_array[i]=grades[i];
grades=new_size_array;
}
pointer++;
grades[pointer]=new_element;
calculate();
return true;
}
public E[] getter()
{
E[] result = (E[]) new Comparable[pointer+1];
for (int i=0; i<=pointer;i++)
result[i]=grades[i];
return result;
}
public void to_string(){
System.out.println(Arrays.toString(getter()));
}
}
The problem is almost certainly this definition:
public class StudentGradesGeneric <E extends Comparable<E>> extends Number
This defines a new class named StudentGradesGeneric with a type argument named E that is required to extend Comparable<E>. StudentGradesGeneric also extends Number.
That last part is wrong: there's no reason for StudentGradesGeneric itself to extend Number (it's conceivable that someone would want that, but it'd be unlikely and nothing in your question indicates you do).
What you want is E to extend Number:
public class StudentGradesGeneric <E extends Number & Comparable<E>>
I've not checked the rest of your code and I think you'll find that Number is not as useful a base type as you'd wish, as there's no way, for example to add two generic Number objects and get an object of the same type back.
Related
I need to sort a java list containing objects of type Hotel
List<Hotel> hotelList = new ArrayList<>();
Inside the class I do have the method
#Override
public List<Room> getAvailableRooms() {
return this.rooms;
}
I need to sort my hotelList by the price attribute found in Room class.
Any suggestions?
You should either use a Comparator or implement the Comparable interface
public class Foo implements Comparable<ToSort> {
private int val;
public Foo(int val){
this.val = val;
}
#Override
public int compareTo(ToSort f) {
if (val > f.val) {
return 1;
}
else if (val < f.val) {
return -1;
}
else {
return 0;
}
}
Read more here
https://dzone.com/articles/sorting-java-arraylist
it's my first time ever posting on StackOverFlow, because I'm truly desperate right now. I couldn't find an answer for my problem anywhere, so long story short, I have some kind of project for my Data Structures course. The project had 2 parts. The first part was implementing a Sorted Array Bag/ Sorted Collection for some problem. We are using java.
The second part is where I do actually have a lot of problems. So the main idea is implementing a doubly-linked list from the sorted-array bag/ sorted collection and in a way that I would just switch sorted array bag with doubly-linked list in my main and everything should work the way it was working before.
The main thing about the SortedArrayBag is as far as I understand using a Comparator when you declare the SortedArrayBag in your main, and it looks like this:
SortedBag<Grupe> al = new SortedArrayBag<>(new ComparatorVot());
al.add(new Grupe("gr1", 5));
al.add(new Grupe("gr2", 7));
The sorted collection/sorted array bag was implemented by my teacher because there is no such data structure in Java, here is her implementation:
public class SortedArrayBag<T> implements SortedBag<T> {
private ArrayList<T> elemente;
private Comparator<T> relatie;
public SortedArrayBag(Comparator<T> rel) {
this.elemente = new ArrayList<>();
this.relatie = rel;
}
public void add(T elem) {
int index = 0;
boolean added = false;
while (index < this.elemente.size() && added == false) {
T currentElem = this.elemente.get(index);
if (relatie.compare(currentElem, elem) < 0) {
index++;
} else {
this.elemente.add(index, elem);
added = true;
}
}
if (!added) {
this.elemente.add(elem);
}
}
public void remove(T elem) {
boolean removed = this.elemente.remove(elem);
}
public int size() {
return this.elemente.size();
}
public boolean search(T elem) {
return this.elemente.contains(elem);
}
public Iterator<T> iterator() {
return this.elemente.iterator();
}
}
And the SortedBag interface looks like this
public interface SortedBag<T> {
public void add(T elem);
public void remove(T elem);
public int size();
public boolean search(T elem);
public Iterator<T> iterator();
}
Also in case it helps, the comparator looks like this:
public class ComparatorVot implements Comparator<Grupe> {
public int compare(Grupe o1, Grupe o2) {
Grupe gr1 = (Grupe) o1;
Grupe gr2 = (Grupe) o2;
if (gr1.getNrPersoane() / 2 + 1 == gr2.getNrPersoane() / 2 + 1) {
return 0;
} else if (gr1.getNrPersoane() / 2 + 1 > gr2.getNrPersoane() / 2 + 1) {
return 1;
} else {
return -1;
}
}
}
So, I tried my best implementing doublyLinkedList using a SortedArrayBag, this is what I did, also if it helps making my code more clear, prim=first, ultim=last, urmator=next, anterior=previous
import java.util.Iterator;
public class LDI {
private Nod prim;
private Nod ultim;
//private int lungime;
public LDI() {
this.prim = null;
this.ultim = null;
//this.lungime = 0;
}
public class Nod {
private int elem;
private int frecventa;
private Nod urmator;
private Nod anterior;
public Nod(int e, int f) {
this.elem = e;
this.frecventa = f;
this.urmator = null;
this.anterior = null;
}
}
public void add(int elem, int frecventa) {
Nod nodNou = new Nod(elem, frecventa);
nodNou.elem = elem;
nodNou.frecventa = frecventa;
if (prim == null) {
this.prim = nodNou;
this.ultim = nodNou;
} else if (frecventa <= prim.frecventa) {
nodNou.urmator = prim;
this.prim.anterior = nodNou;
this.prim = nodNou;
} else if (frecventa >= prim.frecventa) {
nodNou.anterior = prim;
for (; nodNou.anterior.urmator != null; nodNou.anterior = nodNou.anterior.urmator) {
if (nodNou.anterior.urmator.frecventa > frecventa)
break;
}
nodNou.urmator = nodNou.anterior.urmator;
if (nodNou.anterior.urmator != null) {
nodNou.anterior.urmator.anterior = nodNou;
}
nodNou.anterior.urmator = nodNou;
nodNou.anterior = nodNou.anterior;
}
}
public void remove() {
if (this.prim != null) {
if (this.prim == this.ultim) {
this.prim = null;
this.ultim = null;
} else
this.prim = this.prim.urmator;
this.prim.anterior = null;
}
}
public int size() {
int count = 0;
for (Nod nodNou = prim; nodNou != null; nodNou = nodNou.urmator)
count++;
return count;
}
public class MyIterator {
private Nod curent;
public MyIterator() {
this.curent = prim;
}
public void urmator() {
this.curent = this.curent.urmator;
}
public int getElem() {
return this.curent.elem;
}
public boolean valid() {
if (this.curent != null) {
return true;
} else {
return false;
}
}
}
public Iterator iterator() {
return new MyIterator();
}
}
The thing is, it doesn't work, I have no idea how to make my data structure able to receive the Comparator I used and also the Iterator doesn't work. If you have any idea how to make this work, please do help me.
Suppose I have the following compareTo:
public int compareTo(RandomClass o) {
if (this.value() < o.value()) {
return -1;
} else if (this.value() > o.value()) {
return 1;
} else {
return 0;
}
}
I want to know the exact number of comparisons when I call Arrays.sort(randomClassArray), where randomClassArray has 100 objects?
For me the best approach is to use a decorator of type Comparator that will count the total of times it is called something like:
public class Counter<T> implements Comparator<T> {
private final AtomicInteger counter;
private final Comparator<T> comparator;
public Counter(Comparator<T> comparator) {
this.counter = new AtomicInteger();
this.comparator = comparator;
}
#Override
public int compare(final T o1, final T o2) {
counter.incrementAndGet();
return comparator.compare(o1, o2);
}
public int getTotalCalled() {
return this.counter.get();
}
}
Then you will provide your own comparator to it and use Arrays.sort(T[], Comparartor) to sort your array, as next:
Counter<SomeClass> counter = new Counter<>(myComparator);
Arrays.sort(randomClassArray, counter);
int totalCalled = counter.getTotalCalled();
Consider binding an atomic integral type field called counter, say to your collection. Set it to zero before your sorting algorithm, then increment it by one (atomically) inside compareTo.
It needs to be atomic in case your sorting algorithm is parallelised. I'd shy away from making compareTo synchronized as that will probably ruin the benefit of any parallelisation.
Perhaps it needs to be incremented twice for the return values of 1, 0?
declare a public static int variable and increment it in the compareTo() method.
After Arrays.sort(randomClassArray) print the variable and reset it.
Set a global counter.
Below is my code:
public class ComparatorCount {
static int counter = 0;
public static void main(String[] args) {
Random random = new Random();
List<RandomClass> randomClassList = new ArrayList<>();
for(int i = 0 ; i < 100 ; i++) {
RandomClass rc = new RandomClass();
rc.setValue(i + random.nextInt(100));
randomClassList.add(rc);
}
Collections.sort(randomClassList);
randomClassList.forEach(x -> System.out.println(x));
System.out.println("compare " + counter + " times in total.");
}
static class RandomClass implements Comparable<RandomClass> {
private int value;
public int value() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String toString() {
return "randomClass : " + value;
}
#Override
public int compareTo(RandomClass o) {
counter++;
if (this.value() < o.value()) {
return -1;
} else if (this.value() > o.value()) {
return 1;
} else {
return 0;
}
}
}
}
You could write your own class implementing Comparator<RandomClass> interface:
public class CustomComparator implements Comparator<RandomClass> {
private final AtomicInteger counter;
public CustomComparator() {
this.counter = new AtomicInteger(0);
}
#Override
public int compare(RandomClass val1, RandomClass val2) {
this.counter.incrementAndGet();
if (val1.value() < val2.value()) {
return -1;
} else if (val1.value() > val2.value()) {
return 1;
}
return 0;
}
public int getNumberOfOperations() {
return this.counter.intValue();
}
}
Then call static <T> void sort(T[] a, Comparator<? super T> c) function with the following arguments:
CustomComparator comparator = new CustomComparator();
Arrays.sort(randomClassAray, comparator);
System.out.println("Number of operations = " + String.valueOf(comparator.getNumberOfOperations()));
Try this.
public class ComparatorCounter<T extends Comparable<T>> implements Comparator<T> {
public int counter = 0;
#Override
public int compare(T o1, T o2) {
++counter;
return o1.compareTo(o2);
}
}
and
RandomClass[] array = new RandomClass[9];
// fill array
ComparatorCounter<RandomClass> comp = new ComparatorCounter<>();
Arrays.sort(array, comp);
System.out.println("compare count=" + comp.counter);
I have two ArrayLists. How can I compare the elements in the arraylists and create a new list with the results?
I need to iterate through the list to actually get its results and compare. How can I do it in Java?
Any help is appreciated.
Thanks
You can compare by implementing Comparator class.You can understand by below example in which Two Time class is getting compared.
class Time
{
int hours,minutes,seconds;
public Time(int hours,int minutes,int seconds)
{
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
}
public int getHours()
{
return this.hours;
}
public int getMinutes()
{
return this.minutes;
}
public int getSeconds()
{
return this.seconds;
}
public String toString()
{
return String.format("%d:%02d:%02d %s",((hours==0||hours==12)? 12:hours%12),this.minutes,this.seconds,((hours>=12)?"PM":"AM"));
}
}
class TimeComparator implements Comparator<Time>
{
public int compare(Time t1,Time t2)
{
int hours=t1.getHours()-t2.getHours();
int minutes=t1.getMinutes()-t2.getMinutes();
int seconds=t1.getSeconds()-t2.getSeconds();
if(hours>0)
return 1;
else if(hours<0)
return -1;
if(minutes>0)
return 1;
else if(minutes<0)
return -1;
if(seconds>0)
return 1;
else if(seconds<0)
return -1;
return 0;
}
public boolean equals(Object obj)
{
return true;
}
}
After this you can use Collections class to use any method like sorting or search.
I hope that the following chunck of code will get you started.
import java.util.ArrayList;
class Compare {
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
a.add("Hello");
a.add("Goodbye");
ArrayList<String> b = new ArrayList<String>();
b.add("Hello");
b.add("Bye");
if (a.size() != b.size()) {
System.out.println("Arrays must have the same size");
return;
}
ArrayList<Boolean> results = new ArrayList<Boolean>();
for(int i = 0; i < a.size(); ++i)
results.add(a.get(i).equals(b.get(i)));
for(int i = 0; i < a.size(); ++i)
System.out.println(results.get(i));
}
}
I'm using Eclipse and I'm using Java. My objective it's to sort a vector, with the bogoSort method
in one vector( vectorExample ) adapted to my type of vector and use the Java sort on other vector (javaVector) and compare them.
I did the tests but it did't work, so I don't know what is failing.
*Note: there are few words in spanish: ordenado = sorted, Ejemplo = Example, maximo = maximun, contenido = content.
EjemploVector class
package vector;
import java.util.NoSuchElementException;
import java.util.Vector;
import java.util.Iterator;
public class EjemploVector <T> {
protected T[] contenido;
private int numeroElementos;
#SuppressWarnings("unchecked")
public EjemploVector () {
contenido = (T[]) new Object[100];
numeroElementos = 0;
}
#SuppressWarnings("unchecked")
public EjemploVector (int maximo) {
contenido = (T[]) new Object[maximo];
numeroElementos = 0;
}
public String toString(){
String toString="[";
for (int k=0; k<numeroElementos;k++){
if (k==numeroElementos-1){
toString = toString + contenido[k].toString();
} else {
toString = toString + contenido[k].toString()+", ";
}
}
toString = toString + "]";
return toString;
}
public boolean equals (Object derecho){
if (!(derecho instanceof Vector<?>)) {
return false;
} else if (numeroElementos != ((Vector<?>)derecho).size()) {
return false;
} else {
Iterator<?> elemento = ((Vector<?>)derecho).iterator();
for (int k=0; k<numeroElementos;k++){
if (!((contenido[k]).equals (elemento.next()))) {
return false;
}
}
return true;
}
}
public void addElement (T elemento){
contenido[numeroElementos++]= elemento;
}
protected T[] getContenido(){
return this.contenido;
}
protected T getContenido (int k){
return this.contenido[k];
}
#SuppressWarnings("unchecked")
protected void setContenido (int k, Object elemento){
this.contenido[k]= (T)elemento;
}
EjemploVectorOrdenadoClass
package vector.ordenado;
import java.util.Arrays;
import java.util.Random;
import vector.EjemploVector;
public class EjemploVectorOrdenado<T extends Comparable<T>> extends EjemploVector<T> {
private boolean organized;
public EjemploVectorOrdenado() {
super();
organized = true;
}
public EjemploVectorOrdenado(int maximo) {
super(maximo);
organized = true; //
}
public boolean getOrdenado() {
return this.organized;
}
// Method bogoSort
public void bogoSort() {
if (!this.organized) {
if (this.size() > 0) {
Random generator;
T tempVariable;
int randomPosition;
do {
generator = new Random();
for (int i = 0; i < this.size(); i++) {
randomPosition = generator.nextInt(this.size());
tempVariable = contenido[i];
contenido[i] = contenido[randomPosition];
contenido[randomPosition] = tempVariable;
}
} while (!organized);
}
}
this.organized = true;
}
public void addElement(T elemento) {
super.addElement(elemento);
if (organized && this.size() > 1) {
T penultimo = this.getContenido(this.size() - 2);
T ultimo = this.getContenido(this.size() - 1);
organized = penultimo.compareTo(ultimo) <= 0;
}
}
}
ElementoTest class
package elementos;
import java.io.Serializable;
public class ElementoTest implements Comparable<ElementoTest>, Serializable {
private static final long serialVersionUID = -7683744298261205956L;
private static int numeroElementosTest = 0;
private int clave;
private int valor;
public ElementoTest(int i){
this.clave = i;
this.valor = numeroElementosTest;
numeroElementosTest++;
}
public String toString(){
return ("(" + this.clave + "," + this.valor + ")");
}
public boolean equals (Object derecho){
if (!(derecho instanceof ElementoTest)) {
return false;
} else {
return clave == ((ElementoTest)derecho).clave;
}
}
public char getClave(){
return this.clave;
}
public int getValor(){
return this.valor;
}
#Override
public int compareTo(ElementoTest elemento) {
if (elemento == null){
return -1;
} else if (this.equals(elemento)){
return 0;
} else if (clave < elemento.clave){
return -1;
} else {
return 1;
}
}
}
TESTS
The first it's a stupid test, because it puts elements in order so... really the methods arenĀ“t doing anything, java just compare and it gives correct
I tried to make an unsorted vector adding elements but there appears the java.lang.ClassCastException: [Ljava.... etc.
package vector.ordenado;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Vector;
import org.junit.Before;
import org.junit.Test;
import elementos.ElementoTest;
public class EjemploVectorOrdenadoTest {
private Vector<ElementoTest> vectorJava;
private EjemploVectorOrdenado<ElementoTest> vectorExample;
#Before
public void setUp() throws Exception {
vectorJava = new Vector<ElementoTest>(100);
vectorExample = new EjemploVectorOrdenado<ElementoTest>(100);
}
#Test
public void testSortFailTest() {
for (char c = 'a'; c < 'g'; c++) {
vectorJava.addElement(new ElementoTest(c));
vectorExample.addElement(new ElementoTest(c));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
#Test
public void testSort() {
{
vectorJava.addElement(new ElementoTest(1));
vectorJava.addElement(new ElementoTest(3));
vectorJava.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(3));
vectorExample.addElement(new ElementoTest(2));
vectorExample.addElement(new ElementoTest(1));
}
Collections.sort(vectorJava);
vectorExample.bogoSort();
assertTrue(vectorExample.equals(vectorJava));
assertTrue(vectorExample.getOrdenado());
}
}
Sorry, for the problems and thanks.
The problem is that your test class ElementoTest should implement the Comparable interface. Or you need to provide a Comparator during your comparison.
Does your class ElementtoTest implement Comparable?
If not, it needs to.
I'm suspecting it doesn't, because that's exactly what would cause this error. you'll need to add implements Comparable and then override the int compareTo(Elementtotest e) method, where you specify what criteria you'd like to order the objects based on.