I try to make a thread safe class which allows to follow the scan of something. My class is:
import java.util.concurrent.atomic.AtomicInteger;
public class ScanInProgress {
private final Integer scanId;
private final int nbScans;
private AtomicInteger nbResponses = new AtomicInteger(0);
private AtomicInteger nbErrors = new AtomicInteger(0);
public ScanInProgress(Integer scanId, int nbSites) {
this.scanId = scanId;
this.nbScans = nbSites;
}
public Integer getScanId() {
return scanId;
}
public boolean addSuccess() {
addResponse();
return isDone();
}
public boolean addError() {
addResponse();
nbErrors.incrementAndGet();
return isDone();
}
private void addResponse() {
nbResponses.incrementAndGet();
}
private boolean isDone() {
return nbResponses.get() == nbScans;
}
public int getNbSuccesses() {
return nbResponses.get() - nbErrors.get();
}
public int getNbResponses() {
return nbResponses.get();
}
}
I have the following unit tests class:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ScanInProgressTest {
#Test
public void testConcurrency() throws Exception {
// given
Integer scanId = 1;
int nbScans = 500_000;
ScanInProgress scanInProgress = new ScanInProgress(scanId, nbScans);
// when
for (int i = 1; i <= nbScans / 2; i++) {
new AddError(scanInProgress).start();
new AddSuccess(scanInProgress).start();
}
Thread.sleep(1000);
// then
assertEquals(nbScans, scanInProgress.getNbResponses());
assertEquals(nbScans / 2, scanInProgress.getNbSuccesses());
}
private class AddError extends Thread {
private ScanInProgress scanInProgress;
public AddError(ScanInProgress scanInProgress) {
this.scanInProgress = scanInProgress;
}
#Override
public void run() {
int before = scanInProgress.getNbResponses();
scanInProgress.addError();
int after = scanInProgress.getNbResponses();
assertTrue("Add error: before=" + before + ", after=" + after, before < after);
}
}
private class AddSuccess extends Thread {
private ScanInProgress scanInProgress;
public AddSuccess(ScanInProgress scanInProgress) {
this.scanInProgress = scanInProgress;
}
#Override
public void run() {
int beforeResponses = scanInProgress.getNbResponses();
int beforeSuccesses = scanInProgress.getNbSuccesses();
scanInProgress.addSuccess();
int afterResponses = scanInProgress.getNbResponses();
int afterSuccesses = scanInProgress.getNbSuccesses();
assertTrue("Add success responses: before=" + beforeResponses + ", after=" + afterResponses, beforeResponses < afterResponses);
assertTrue("Add success successes: before=" + beforeSuccesses + ", after=" + afterSuccesses, beforeSuccesses < afterSuccesses);
}
}
}
When I run my test I can see regularly this error in logs:
Exception in thread "Thread-14723" java.lang.AssertionError: Add success successes: before=7362, after=7362
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.assertTrue(Assert.java:41)
The assertion lets me think that when I call the method scanInProgress.addSuccess() and then scanInProgress.getNbSuccesses(), the instruction in first method nbResponses.incrementAndGet() is not yet acknowledged whereas the instruction in second method nbResponses.get() returns something.
What can I do to correct this ?
As far as I unsterstand the problem I think you need to use locks. Before you get or set an variable you need to aquire a lock. This way a variable can't be set and read at the same time. You get something like the code below.
public final static Object LOCK = new Object();
private int yourvariable;
public void setVar(int var){
synchronized(LOCK){
yourvariable = var;
}
}
public int getVar(){
int toReturn;
synchronized(LOCK){
toReturn = yourvariable;
}
return toReturn;
}
note: If your ScanInProgessClass is the only the ScanInProgressClass class, you can use this instead of a LOCK object.
Related
I'm currently teaching myself Java from a textbook, and found a piece of code that I don't understand - why does the final variable id change it's value?
import static net.mindview.util.Print.*;
class Shared {
private int refcount = 0;
private static int counter = 0;
private final int id = counter++;
public Shared() {
print("Creating " + this);
}
public void addRef() { refcount++; }
protected void dispose() {
if(--refcount == 0)
print("Disposing " + this);
}
protected void finalize() {
if(refcount != 0)
print("Error: object is not properly cleaned-up!");
}
public String toString() { return "Shared " + id; }
}
class Composing {
private Shared shared;
private static int counter = 0;
private final int id = counter++;
public Composing(Shared shared) {
print("Creating " + this);
this.shared = shared;
this.shared.addRef();
}
protected void dispose() {
print("disposing " + this);
shared.dispose();
}
public String toString() { return "Composing " + id; }
}
public class E13_VerifiedRefCounting {
public static void main(String[] args) {
Shared shared = new Shared();
Composing[] composing = { new Composing(shared),
new Composing(shared), new Composing(shared),
new Composing(shared), new Composing(shared) };
for(Composing c : composing)
c.dispose();
This:
private static int counter = 0;
private final int id = counter++;
public Shared() {
print("Creating " + this);
}
is the same as this:
private static int counter = 0;
private final int id;
public Shared() {
id = counter++;
print("Creating " + this);
}
That is, the id is assigned every time the constructor executes, with the side effect that counter is incremented.
id is an instance variable, so each instance of shared gets its own id value.
private final int id = counter++;
If by change you are asking why does the value of id is counter + 1 instead of just counter, that's because first the sum counter + 1 is calculated, and then it is set into id. After that, the value of id cannot change.
I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState() {
if (varPass == 0) {
return isOff;
} else {
return isOn;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}
I have started experimenting with the Jenetics library, however I am having some issues with trying to make a very easy "custom" set of gene/chromosomes.
What I tried to do was to create a custom chromosome with a different (random) number of custom genes inside. The genes simply contain an integer value, just for the sake of simplicity. For the same simplicity, the contents of a gene can only be numbers ranging from 0 to 9 and a Gene is considered valid only if it does NOT contain the number 9 (again, retardedly simple, but I just wanted to make them custom)
Here is my code:
CustomGene:
public class CustomGene implements Gene<Integer, CustomGene> {
private Integer value;
private CustomGene(Integer value) {
this.value = value;
}
public static CustomGene of(Integer value) {
return new CustomGene(value);
}
public static ISeq<CustomGene> seq(Integer min, Integer max, int length) {
Random r = RandomRegistry.getRandom();
return MSeq.<CustomGene>ofLength(length).fill(() ->
new CustomGene(random.nextInt(r, min, max))
).toISeq();
}
#Override
public Integer getAllele() {
return value;
}
#Override
public CustomGene newInstance() {
final Random random = RandomRegistry.getRandom();
return new CustomGene(Math.abs(random.nextInt(9)));
}
#Override
public CustomGene newInstance(Integer integer) {
return new CustomGene(integer);
}
#Override
public boolean isValid() {
return value != 9;
}
}
CustomChromosome:
import org.jenetics.Chromosome;
import org.jenetics.util.ISeq;
import org.jenetics.util.RandomRegistry;
import java.util.Iterator;
import java.util.Random;
public class CustomChromosome implements Chromosome<CustomGene> {
private ISeq<CustomGene> iSeq;
private final int length;
public CustomChromosome(ISeq<CustomGene> genes) {
this.iSeq = genes;
this.length = iSeq.length();
}
public static CustomChromosome of(ISeq<CustomGene> genes) {
return new CustomChromosome(genes);
}
#Override
public Chromosome<CustomGene> newInstance(ISeq<CustomGene> iSeq) {
this.iSeq = iSeq;
return this;
}
#Override
public CustomGene getGene(int i) {
return iSeq.get(i);
}
#Override
public int length() {
return iSeq.length();
}
#Override
public ISeq<CustomGene> toSeq() {
return iSeq;
}
#Override
public Chromosome<CustomGene> newInstance() {
final Random random = RandomRegistry.getRandom();
ISeq<CustomGene> genes = ISeq.empty();
for (int i = 0; i < length; i++) {
genes = genes.append(CustomGene.of(Math.abs(random.nextInt(9))));
}
return new CustomChromosome(genes);
}
#Override
public Iterator<CustomGene> iterator() {
return iSeq.iterator();
}
#Override
public boolean isValid() {
return iSeq.stream().allMatch(CustomGene::isValid);
}
}
Main:
import org.jenetics.Genotype;
import org.jenetics.Optimize;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.util.Factory;
import org.jenetics.util.RandomRegistry;
import java.util.Random;
public class Main {
private static int maxSum = - 100;
private static Integer eval(Genotype<CustomGene> gt) {
final int sum = gt.getChromosome().stream().mapToInt(CustomGene::getAllele).sum();
if(sum > maxSum)
maxSum = sum;
return sum;
}
public static void main(String[] args) {
final Random random = RandomRegistry.getRandom();
Factory<Genotype<CustomGene>> g =
Genotype.of(CustomChromosome.of(CustomGene.seq(0, 9, Math.abs(random.nextInt(9)) + 1)));
Engine<CustomGene, Integer> engine = Engine
.builder(Main::eval, g)
.optimize(Optimize.MAXIMUM)
.populationSize(100)
.build();
Genotype<CustomGene> result = engine.stream().limit(10000)
.collect(EvolutionResult.toBestGenotype());
System.out.println(eval(result));
result.getChromosome().stream().forEach(i -> {
System.out.print(i.getAllele() + " ");
});
System.out.println();
System.out.println(maxSum);
}
}
I do not understand why I get this output:
13 (evaluated result)
1 8 0 4 (all the alleles form the genes of the chosen chromosome)
32 (the actual maximum fitness found)
We can clearly see a difference between the genotype which had the biggest fitness function and the chosen genotype. Why?
I know I'm doing something wrong and it's probably a silly mistake, but I really can't seem to understand what I am doing wrong. Could you please help me out?
Lots of thanks!
As posted by the creator of the library here, the answer was:
you violated the contract of the Chromosome.newInstance(ISeq) method. This method must return a new chromosome instance. After fixing this
#Override
public Chromosome<CustomGene> newInstance(ISeq<CustomGene> iSeq) {
return new CustomChromosome(iSeq);
}
Hello I just want to ask how should i get the codes function into a method which is run by the main at the moment! Basically so that I can activate the working method from the main instead. I am new to programming so I am having quite a bit of trouble grasping everything properly
package bla_bla;
import java.io.IOException;
import java.util.ArrayList;
import java.util.*;
import javax.swing.text.html.parser.Element;
import org.codehaus.jackson.map.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.jsoup.select.Evaluator.Id;
import org.json.*;
import argo.saj.InvalidSyntaxException;
public class supermonkey {
private static ArrayList<BugsList> bugsList;
private static ArrayList<BugsList> bugbug;
public static void main(String args[]) throws IOException {
bugsList = new ArrayList<BugsList>();
bugbug = new ArrayList<BugsList>();
Document doc = Jsoup.connect("https://bugzilla.mozilla.org/rest/bug?product=Input&f1=bug_mentor&o1=isnotempty").get();
String rawData = doc.body().text();
// System.out.println(title);
JSONObject obj = new JSONObject(rawData);
// System.out.println(obj);
System.out.println(obj.get("bugs"));
JSONArray jsonMainArr = new JSONArray(obj.get("bugs").toString());
for (int i = 0; i < jsonMainArr.length(); i++) { // **line 2**
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
JSONObject assigned = childJSONObject.getJSONObject("assigned_to_detail");
// JSONObject assigned2 = childJSONObject.getJSONObject("assigned_to_detail");
int id = assigned.getInt("id");
BugsList bug = new BugsList();
BugsList bug2 = new BugsList();
bug.setId(id);
String severity = childJSONObject.getString("severity");
String resolution = childJSONObject.getString("resolution");
String summary = childJSONObject.getString("summary");
String component = childJSONObject.getString("component");
bug.setSeverity(severity);
bug.setResolution(resolution);
bug.setSummary(summary);
bug.setComponent(component);
bugsList.add(bug);
// String severity = assigned.getString();
// System.out.println("sss "+ assigned);
}
getComponent("Code Quality");
// getSeverity(524276);
// getResolution(524276);
// getSummary(524276);
}
public static void getSeverity(int id){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getId() == id){
System.out.println("The id exists in the list " + bugsList.get(i).getSeverity());
}
}
}
public static void getResolution(int id){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getId() == id){
System.out.println("The id exists in the list and The resolution is" + bugsList.get(i).getResolution());
}
}
}
public static void getSummary(int id){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getId() == id){
System.out.println("The comp.. exists in the list and The summary is " + bugsList.get(i).getSummary());
}
}
}
// Current used method
public static ArrayList<BugsList> getComponent(String component){
for(int i =0;i<bugsList.size(); i++){
if(bugsList.get(i).getComponent().equals(component)){
System.out.println("(Code Quality) component contains summary " + bugsList.get(i).getSummary() +" /The resolution is " +
bugsList.get(i).getResolution() + " /Severity is " + bugsList.get(i).getSeverity());
bugbug.add(bugsList.get(i));
}
}
return bugbug;
}
}
package bla_bla;
public class BugsList {
private String severity;
private int id;
private String resolution;
private String summary;
private String component;
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
I think I understand you problem. You write your code into the main function and that not the solution.
Your main function should look something like that:
public static void main(String args[]) throws IOException {
Supermonkey supermonkey = new Supermonkey();
supermonkey.getComponent("componennt name ");
}
Your Class is Supermonkey and you create an instance call supermonkey (sometime people use mySupermonkey) . There is only one instance of this class that will use.
Then into the constructor method you can create everything to build your instance supermonkey as :
public class Supermonkey {
private ArrayList<BugsList> bugsList;
private ArrayList<BugsList> bugbug;
public Supermonkey(){
bugsList = new ArrayList<BugsList>();
bugbug = new ArrayList<BugsList>();
Document doc = Jsoup
.connect(
"https://bugzilla.mozilla.org/rest/bug?product=Input&f1=bug_mentor&o1=isnotempty")
.get();
String rawData = doc.body().text(); // ... partial code add everything about initialisation of your instance
Then you can have a method of this Class Supermonkey
// Current used method
public ArrayList<BugsList> getComponent(String component) {
for (int i = 0; i < bugsList.size(); i++) {
if (bugsList.get(i).getComponent().equals(component)) {
System.out
.println("(Code Quality) component contains summary "
+ bugsList.get(i).getSummary()
+ " /The resolution is "
+ bugsList.get(i).getResolution()
+ " /Severity is "
+ bugsList.get(i).getSeverity());
bugbug.add(bugsList.get(i));
}
}
return bugbug;
}
A this method is call from the public static void main(String args[]) with supermonkey.getComponent("componennt name ");
Also I think about to change the name of Class BugsList it seems to be a BugItem , may be ?
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.