I'm porting some image processing code from C++ to Java. My C++ code has template classes that define mixed-mode image arithmetic. I'm trying to do the same in Java but it's clear that I don't understand the concepts needed to do it. Currently, I'm trying to write a generic method.
private void DoMyRoutine()
{
float[] data = {1.1f,2.2f,3.3f};
Float[] fArr = new Float[data.length]; // Is there a better way to do this?
for(int i = 0; i< data.length;i++)
{
fArr[i] = data[i];
}
fArr = Test(fArr);
}
//*********************************************************************************************
private <T> T[] Test( T[] myData)
{
Float inc = new Float(2.0f);
for(int i=0;i<myData.length;i++)
{
// I can see the myData array values in the debugger
// This clearly doesn't work, is there a method"
myData[i] = inc;
}
return myData;
}
Am I even on the right track? I'm relatively new to Java and still struggling with some of the concepts and syntax.
Related
I'm currently implementing an algorithm that constructs a matrix-pattern based on mathematical formulas. To achieve this I use deeply nested for-loops and alot of if-conditions in it. The problem is, that I cannot split the loop into multiple method without providing a lot of parameters. And for now the code looks like an undesired spaghetti-code.
Here is a small pseudo-example:
int steps = 10;
void evaluate( int numOuterArea , int numInnerArea , int[] solution , int[] factor , int[] indices )
{
int counterA = 0;
int counterB = 0;
for( int outerAreaIter = 0 ; outerAreaIter < numOuterArea ; outerAreaIter++ )
{
for( int curOuterAreaIter = 0 ; curOuterAreaIter < steps ; curOuterAreaIter++ )
{
for( int innerAreaIter = 0 ; innerAreaIter < numInnerArea ; innerAreaIter++ )
{
for( int curInnerAreaIter = 0 ; curInnerAreaIter < curOuterAreaIter ; curInnerAreaIter++ )
{
if( curInnerAreaIter == curOuterAreaIter )
{
// do something with solution, factor or indices
}
else if( /* some other fancy condition */)
{
}
...
}
}
}
}
// similar nested loops follow here
}
If I would write classes/methods for each loop or part of a loop, I have to provide all parameters from evaluate() (which can be even more as shown in the example) and also all previous iterators and possible variables.
Is there a way/common practice/any hints or advice to rewrite such code in a better way?
The simplest way is encapsulation of all parameters in the single object. You can use this object to passing data as sole parameter into evaluation method. Something like this example:
class EvaluationContext {
int numOuterArea;
int numInnerArea;
int[] solution;
int[] factor;
int[] indices;
}
interface Evaluator {
void evaluate(EvaluationContext ctx);
}
class FirstEvaluator implements Evaluator {
void evaluate(EvaluationContext ctx) {
SecondEvaluator e2 = new SecondEvaluator();
for (...) {
e2.evaluate(ctx);
}
}
}
class SecondEvaluator implements Evaluator {
void evaluate(EvaluationContext ctx) {
// evaluate something and put result into context
}
}
A simple design pattern is a Method Object. Simply write a class which is responsible for this calculation. You then can have fields that simply store intermediate results during that calculation. With this approach, you do not need to pass any arguments.
Example:
class EvaluateMethod {
private final int numOuterArea;
private final int numInnerArea;
private final int[] solution;
private final int[] factor;
private final int[] indices;
// place fields for intermediate results here
EvaluateMethod(int numOuterArea, int numInnerArea, int[] solution, int[] factor, int[] indices) {
// assign all parameter to fields here
}
void execute() {
// Your method body as before comes here.
// But you can extract methods easily.
}
}
One additional note: You cannot reuse an instance of this class. I call them one-shot-objects that must be instantiated, used, and discarded.
I have below code.
Complex[] time1Dummy = new Complex[time1.size()];
Complex[] freq1 = new Complex[time1.size()];
System.out.println("Size of time1:" +time1.size());
for(int i = 0; i < time1.size(); i++) {
time1Dummy[i].setRe(time1.get(i));
time1Dummy[i].setIm(0.00);
}
In this, Complex is the class which contains
private static Double re; // the real part
private static Double im; // the imaginary part`
Here, I am trying to assign values from array list time1 to complex value functions.
I am running this code in eclipse 4.3.2. Can someone please help me out in this?
My guess is you are getting null pointer exceptions? See the first line I added within the for loop (assuming Complex has a default constructor).
Complex[] time1Dummy = new Complex[time1.size()];
Complex[] freq1 = new Complex[time1.size()];
System.out.println("Size of time1:" +time1.size());
for(int i = 0; i < time1.size(); i++) {
time1Dummy[i] = new Complex();
time1Dummy[i].setRe(time1.get(i));
time1Dummy[i].setIm(0.00);
}
The first two lines of your code create arrays of Complex objects, but each element does not yet have an object created within it. You need to explicitly create an object first.
Also the attributes should not be static:
private Double re; // the real part
private Double im; // the imaginary part`
I have been thinking for a while about this issue. I am in need of a class that can take in some double[][] array and then store this array for future usage. The only storage option that I can think of is storing a double[][] in an ArrayList<>() of double[][]'s.
I did implement it as follows:
public class AddToArray {
public String[] parameterNames;
public ArrayList<double[][]> parametersToChange;
public AddToArray(String[] parameterNames){
this.parameterNames = parameterNames;
}
public void addToArray(double[][] parametersToChange) throws InsufficientInputException
for(int i = 0; i < parametersToChange.length; i++){
if(parametersToChange[i].length != this.parameterNames.length)
throw new InsufficientInputException("DATA DIMENSION MISMATCH");
}
// This below gives nullpointexception.
this.parametersToChange.add(parametersToChange);
}
I call by this example:
double[][] parametersToChange = {{0.005,0.006},{0.007,0.008}};
String[] par = {"SI1","SI2"};
AddToArray abc = new AddToArray(par);
abc.addToArray(parametersToChange);
System.out.println(abc.parametersToChange.get(0)[0][0]); // this would (in my ideal world) print out 0.005
I receive a null pointer exception for this call and I am thinking that its not possible to make an ´ArrayList´. What other options do I have, I really can't figure this one out?
did you initialize the arraylist?
parametersToChange = new ArrayList<>();
You forgot to initialize parametersToChange
Because of the way generics are implemented in Java (type erasure), arrays and generics don't work well together.
Joshua Bloch has a discussion on the topic in Effective Java, you can find that section here.
In this I am trying to sort out the intV and stringV using this getSmallestValue method. Tried different ideas but does not seems to be working. Anyone have any bright ideas how to implement this getSmallestValue method?
public class test {
public static Comparable getSmallestValue(Vector<Comparable> a) {
Comparator com = Collections.reverseOrder();
Collections.sort(a, com);
return (Comparable) a;
}
public static void main(String[] args) {
Vector<Comparable> intV = new Vector<Comparable>();
intV.add(new Integer(-1));
intV.add(new Integer(56));
intV.add(new Integer(-100));
int smallestInt = (Integer) getSmallestValue(intV);
System.out.println(smallestInt);
Vector<Comparable> stringV = new Vector<Comparable>();
stringV.add("testing");
stringV.add("Pti");
stringV.add("semesterGoes");
String smallestString = (String) getSmallestValue(stringV);
System.out.println(smallestString);
}
}
Welcome to StackOverflow.
Your basic problem is that you have tried to turn a Vector into an Integer which you cannot do.
What is likely to be more useful is to use the first element of the vector.
I would suggest you
use List instead of Vector.
I wouldn't use manual wrapping
define the getSmallestValue using generics to avoid confusion.
Here are two ways you could implement this method.
public static <N extends Comparable<N>> N getSmallestValue(List<N> a) {
Collections.sort(a);
return a.get(0);
}
public static <N extends Comparable<N>> N getSmallestValue2(List<N> a) {
return Collections.min(a);
}
List<Integer> ints = Arrays.asList(-1, 56, -100);
int min = getSmallestValue(ints);
// or
int min = Collections.min(ints);
Use Collections.min().You can check out the source if you you want to know how it's implemented.
Vector<Integer> v=new Vector<Integer>();
v.add(22);v.add(33);
System.out.println(Collections.min(v));
Ok, here is the code and then the discussion follows:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop,
the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same "experiment" with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the currentRow array. Move that inside the row loop and it should behave more like you expect.
Specifically, the assignment in setCurrentRow does not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the same int[] array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.
i don' t want to sound condescending, but always try to remember tip #26 from the excellent pragmatic programmer book
select isn't broken
it is very rare to find a java bug. keeping this in mind often helps me to look over my code again, turn it around, and shake out the loose bits until i finally discover where i was wrong. of course asking for help early enough is very encouraged, too :)