I have a class called Variable
Class Variable{ private String name; private int[] domain; //...etc}
which represents variable in specific structure (constraint satisfaction problem).
I have instantiated set of variables in ArrayList< Variable > and filled up an array of integers.
ArrayList<Variable> vars=new ArrayList<Variable>();
Variable a=new Variable("A",new int[]{1,2});
vars.add(a);
// Define all variables;
int[] cons=new int[vars.size()];
for(int i=0;i<cons.length;i++)
cons[i]=number_of_constraints(vars.get(i));
// cons contains number of involved constraints for each variable
Now I need to sort them descending based on the number of constraints.
In other words: Given list of Objects [(A,{1,2}) , (B,{3,4}) , (C,{5,6}) ] and an array of integers cons={1,2,0} how to sort the list of objects descending based on the array of integers?
Use a sorted collection like a TreeSet
class Variable {
private String name;
private int[] domain;
};
final Set<Variable> variables = new TreeSet<Variable>( new Comparator<Variable>() {
public int compare(Variable o1, Variable o2) {
//Do comparison here
//return -1 if o1 is less than o2
//1 if o1 is greater than o2
//0 if they are the same
}
});
Now you have a sorted Set of your Variables. This is guaranteed to always be sorted.
If you would like to keep Class Variable intact, the following code will sort the given vars outside:
Collections.sort(vars, new Comparator<Variable>() {
public int compare(Variable var1, Variable var2) {
return var2.number_of_constraints() - var1.number_of_constraints();
}});
If you can change Class Variable, let it implement interface Comparable:
class Variable implements Comparable<Variable> {
//...
public int compareTo(Variable other) {
return this.number_of_constraints() -
other.number_of_constraints();
}
}
Then you can sort vars by:
Collections.sort(vars);
As far as a Variable contains numOfConstraints, according to your code, you can make your Variable class implement Comparable interface, like
public class Variuable implements Comparable<Variable> {
private int numOfConstraints;
public int compareTo(Variable other){
if(this == other) { return 0; }
return (numOfConstraints == other.numOfConstraint) ? 0 : ((numOfConstraints > other.numOfConstraint) ? 1 : -1);
}
}
And then use the utility method java.util.Collections.sort(vars);, that's it.
Your Variable class should implement the Comparable interface,
When it does you should implement the compareTo method.
After that you can sort it by calling the Collection.sort method.
If you want to sort by a permutation if your indexes that's just a matter of creating a new ArrayList and mapping each index to the new index (using a for loop)
Here is such a (generic) method
public static <T> ArrayList<T> permutate(ArrayList<T> origin,int[] permutation){
ArrayList<T> result = new ArrayList<T>(permutation.length);
for(int j=0;j<permutation.length;j++){
result.add(null);
}
for(int i=0;i<permutation.length;i++){
result.set(i, origin.get(permutation[i]));
}
return result;
}
You can do myArrayList= permutate(myArrayList, new int{1,2,3});
Here is example usage in a more basic use case (integers):
public static void main(String... args){
ArrayList<Integer> origin = new ArrayList<>(4);
origin.add(1);
origin.add(2);
origin.add(3);
origin.add(4);
int[] per = new int[]{2,1,3,0};
origin = permutate(origin,per);
System.out.println(Arrays.toString(origin.toArray())); //prints [3,2,4,1], your permutation
}
Related
I would like following effect -> I have object of class FluidArray which will be an array, but depending on the input it will be either int array or String array:
FluidArray XXX = new FluidArray;
XXX.YYY[] might be either String or int
In this case variable YYY of class XXX might be int array or String
Can I somehow declare variable type depending on some choice?
public class FluidArray
{
VarType YYY;
public static void FluidArray(int a)
{
double[] YYY = new double[15];
}
public static void FluidArray(String a)
{
String[] YYY = new String[15];
}
}
Let's say I want to make a sort method.
I input there unsorted array.
I take out sorted array.
The catch is I might want to sort String, double or int array and I don't want to write 3 sorting methods - I thought that my sorting method might work on some defined object and this object will be either String, double int depending on my choice.
I am trying to use Generic type, I got so far sth. like this:
public class test
{
public static void main(String[] args)
{
FluidArray<Integer> arrTest = new FluidArray<>();
arrTest.arr[1]=2;
arrTest.arr[2]=3;
arrTest.arr[3]=4;
}
public static class FluidArray<arrType>
{
public arrType[] arr = (arrType[])new Object[15];
}
}
I don't understand, why I can't get access to the array, compiler ends when inserting first value.
Read up on Generics. Thats what they are supposed to do
I am having trouble creating a constructor that takes an array of Range objects and initializes the list – list should be initialized to an ArrayList of Range. This is the code I have so far from my classes. This constructor method I am trying to create belongs in the multipleGroups Method. I have searched through stackoverflow with no luck for any similar questions but had no luck. Any help is appreciated.
public interface NumberGroup
{
boolean contains(int value);
}
import java.util.Scanner
public class Range implements NumberGroup
{
private int minValue, maxValue;
public Range(int minValue, int maxValue)
{
this.minValue = minValue;
this.maxValue = maxValue;
}
public boolean contains(int value)
{
return minValue <= value && value <= maxValue;
}
}
import java.util.List
import java.util.ArrayList
public class MultipleGroups implements NumberGroup
{
private List<NumberGroup> groupList;
//problem area here.
public MultipleGroups(){
}
public boolean contains(int num)
{
for(NumberGroup group : groupList)
if(group.contains(num))
return true;
return false;
}
the test class tests the constructor with the following:
Range [] myRanges = new Range[3];
myRanges[0] = new Range(5,8);
myRanges[1] = new Range(10,12);
myRanges[2] new Range(1, 6);
group = new MultipleGroups(myRanges);
The following appears to satisfy your requirements:
public MultipleGroups(Range[] ranges){
this.groupList = Arrays.asList(ranges);
}
There are a few things you might consider doing rather than just using this as-is:
You may want to allow varargs invocation (i.e. that you don't have to explicitly create the array at the call site):
public MultipleGroups(Range... ranges){
and you may want to copy the list in order to avoid callers doing nefarious things to the array after they call the constructor:
this.groupList = new ArrayList<>(Arrays.asList(ranges));
I am new to Java and I need some clarification how to approach an issue.
I have a class Epicycle, defined below:
public class Ts_epicycle {
private double epoch;
private double[] tle = new double[10];
}
In another class, Refine I am calling a method that requires the tle array:
// create an instance of Epicycle
Epicycle e = new Epicycle();
methodExample(keps1, keps2, e.tle);
In methodExample, I would be setting the array values for tle
1) What is best way for creating getters/setters for the tle array? (and for the other variable too).
2) In the methodExample, I need to pass in the argument for the whole tle array rather than any particular index of it. How would I go about this.
Apologies if i'm not making it clear.
In fact an interesting question:
In order that altering entries in the gotten array does not alter the original object,
you would need to return a copy of the array. Not so nice.
public class TsEpicycle {
private double epoch;
private double[] tle = new double[10];
public double[] getTLE() {
return Arrays.copyOf(tle, tle.length);
}
}
Alternatively you could use the List class instead of an array:
public class TsEpicycle {
private double epoch;
private List<Double> tle = new ArrayList<>();
public List<Double> getTLE() {
return Collections.unmodifiableList(tle);
}
}
This does not make a copy, but simple disallows at run-time to alter the list.
Here the inefficiency is in the Double objects wrapping doubles.
The best might be to use the new Stream class: for iterating through the doubles:
public class TsEpicycle {
private double epoch;
private double[] tle = new double[10];
public DoubleStream getTLE() {
return Stream.of(tle);
}
}
As a general best practice every field in a class that you need to access from another class should be provided with a getter and (if the object is intended as mutable) a setter.
As well explained by Joop Eggen in his answer is usually a good practice to return a copy or a proxy (for example a List/Collection referencing the array), in order to preserve the state of the original array.
If you want to only allow users to edit the array one at a time, then you can add the synchronized keyword to the method signature. Accessing an array is already thread safe so you don't need anything there
For example:
double getTle(int index) {
return tle[index]
}
synchronized void setTle(int index, double value) {
tle[index] = value;
}
This only allows the method to be called once at a time
your array is an object like any other object in java .
// to declare and initialize your array
private int[] st = new int[10];
//getter and setter
public int[] getSt() {
return st;
}
public void setSt(int[] st) {
this.st = st;
}
//for the last method u can use
public void method(int value)
{
for(int i = 0 ; i<st.lenght ; i++){
st[i] += value; // for exemple
}
I have been having issues with a class named arrayList that represents a list of objects and supports random access to its objects via a numeric position index.
The toString method should build and return a string containing the string representations of the objects currently accessible in the array, and when the logical size is 0; the string is empty.
I use a tester class to call the arrayList class.
public class Tester {
public static void main(String [] args) {
arrayList a1, a2;
a1 = new arrayList();
a2 = new arrayList(5);
a2.size();
System.out.println(a1.toString());
//System.out.println(a2.toString());
}
}
public class arrayList {
private int logicalSize;
private static Object[] array = new Object[0];
private Object[] original;
private Object removedElement;
public arrayList() {
Object[] array = new Object[]{null,null,null,null,null};
}
public arrayList(int i) {
logicalSize = i;
Object[] array = new Object[logicalSize - 1];
}
public arrayList(Object[] array) {
logicalSize = array.length;
Object[] copyArray = array;
}
#Override
public String toString(Object[] array) {
String str = " ";
for(int a = 0; a < logicalSize; a++) {
str = str + array[a];
}
str = str + "\nSize: " + size();
return str;
}
public int size() {
int length = array.length;
return length;
}
}
When the above code is run, I get "arrayList#(memmorylocation)".
I am only using a single dimensional array (the others are for a later part) and have tried various methods to get it to print anything but the location, including removing the loop that should print out values from the toString, and just doing:
System.out.println(a1);
instead of:
System.out.println(a1.toString());
but no matter what I change I still print out its location, and not its value.
How do I print the value instead of the location? I am using the BlueJ IDE.
Because you call the default method toString instead of the one you defined.
System.out.println(a1.toString());
Your method is supposed to receive an array as argument :
public String toString(Object[] array)
so pass in an array, or correctly override the toString() method. Note that using the #Override annotation would have told you that you did not override the method, which would probably made you avoid this mis-understanding.
By the way, by convention java class should start with an uppercase. So by convention, you should name your class ArrayList which already exists in java.util (as you probably know). You should change the name of your class for something more appropriate.
This syntax is repugnant :
Object[] array = new Object[]{null,null,null,null,null};
You want to do instead :
Object[] array = new Object[5];
R call java interface issues.
I knew how to new a java user defined class object as well as call java function in R, some return values can be used directly in R, like integer, string, array, but I have no idea how to access the values of arraylist object.
For example:
public class Bond
{
public String compName;
public long mfAmt;
public Bond() {
}
}
public class test_arr
{
public test_arr()
{
}
public ArrayList<Bond> getArrListDef()
{
ArrayList<Bond> arr = new ArrayList();
Bond bond = new Bond();
bond.compName = "app";
bond.mfAmt = 12;
arr.add(bond);
return arr;
}
public ArrayList<Bond> getArrList(ArrayList<Bond> arr)
{
return arr;
}
}
R call java part:
library(rJava)
test_arr = J('pkg.test_arr')
jarr = test_arr$getArrListDef()
now, the variable jarr is a Java-Object{}, so how can I print the value of jarr in R...also, how to passing a java arraylist object to another function "public ArrayList getArrList(ArrayList arr)".
You can always use the $ convenience operator. It provides an experimental, but simple way of writing code in Java style at the cost of speed. For example to print all elements mfAmt
for (index in seq(test_arr$size())-1)
print(test_arr$get(as.integer(index))$mfAmt)