DataSerializable - serialize and deserialize two dimensional arrays - arrays

There are methods like writeDoubleArray and so on in ObjectDataOutput interface. Of course arrays can be of any dimension and in my case there are some 2D double arrays. How to serialize and then deserialize those? Or maybe because of the way Java handles 2D arrays (not really contiguous blocks in memory) I need to represent a 2D array as 1D one? I mean because of the performance I shouldn't really serialize 2D arrays. Just wrap it into utility object and store like this...?

You have to put the other dimensions yourself first, like the following snippet:
public static class Foo implements DataSerializable {
private double[][] multiDimArray;
#Override
public void writeData(ObjectDataOutput out)
throws IOException {
int firstDim = multiDimArray.length;
out.writeInt(firstDim);
for (int i = 0; i < firstDim; i++) {
out.writeDoubleArray(multiDimArray[i]);
}
}
#Override
public void readData(ObjectDataInput in)
throws IOException {
int firstDim = in.readInt();
multiDimArray = new double[firstDim][];
for (int i = 0; i < firstDim; i++) {
multiDimArray[i] = in.readDoubleArray();
}
}
}
That way it is possible two write any depth of array into a stream. You might be able to abstract that a bit away into two methods (read/write) for easier / more convenient use.

Related

In Java, how do you create a method which takes an array set to a given length?

I know how to create a method,
which takes an array
public void x(int [] arr){}
but I do not know how to set a given length to that array.
If you are trying to make a method that accepts an array, you can structure it like this:
public void x (int[] arr) {
// Code
}
If you want to restrict the length of array the method can accept, you could do something similar to this:
public void x (int[] arr) {
//Check to see if arr is a satisfactory length
if (arr.length > 10) {
//Throw an exception, break, print to the console etc...
}
}
There are some areas where I can't make this explanation as detailed because I don't know what language you're programming in.

Generic methods java for Character and String

I'm looking for a quick solution about an issue in my following code. It is working but not how I wanted.
So,
the idea is that I'm trying to pass an Character class array and convert it into ArrayList. Since I'm using generics, I specified:
public void fromArrayToCollection(T[] a,Collection e)
and I guess this means I can pass what kind of arrays I want, such as Int array, char array,String array,double and so on
But it won't let me pass an character array.
If I am passing a String array is it actually working
Why?
Thank you.
public class FuDaBi {
static class StringToArray{
public <T> void fromArrayToCollection(T[] a,Collection<T> e)
{
for(T x: a)
e.add(x);
}
public <T> void fromStringToArray(T inputString, T[] array )
{
}
}
public static void main(String[] args)
{
Character[] my_array = {'S','A','L','U','T'};
ArrayList<String> result = new ArrayList<String>();
String daniel[] = {"WV","Mercedes"};
StringToArray myimp = new StringToArray();
myimp.fromArrayToCollection(daniel,result);
for(int i=0;i<result.size();i++)
{
System.out.println(result.get(i));
}
}
}
The problem is that I made the ArrayList a String type instead of an Character.
ArrayList result = new ArrayList();

How do you store all permutations (in array) format in a data structure without repeats?

So I'm currently running into an issue: Storing all possible permutations in some data structure (so we don't want to store any repeats).
This is my current implementation:
public static void generatePerms(int[] arr, int start, List list){
if(!list.contains(arr)){
System.out.println(Arrays.toString(arr));
list.add(arr);
}
for(int i = start; i < arr.length; i++){
for(int j=0; j < arr.length; j++){
int[] newArr = swap(i,j,arr);
generatePerms(newArr, start+1, list);
}
}
}
public static int[] swap(int i, int j, int[] arr){
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
return arr.clone();
}
public static void main(String[] args){
generatePerms(new int[]{1,2,3}, 0, new ArrayList<int[]>());
}
Obviously we can use a set, I just used a List here for my own sake of needing to print -- so the contains() is particular to the fact that I am using a list rather than a set. My main issue: Is there a way where one can store the permutations in their array form {[2,3,1], [2,3,1], etc}? Or is this ultimately impossible and I would have to store them as a string 1,2,3 with explicit commas to distinguish the start and ending of a number and then iterate through each string, make an array and then store that. Another possible way is to spit out the repeats; but this probably requires some way of tracking them.
All in all, can arrays of permutations be stored in a data structure without repeats? The code above is Java.

class to return an object array with member attributes that can be accessed from main class

I'm new to Java, so the concepts and terminology are fuzzy, but I'm trying! I need to create a class that will take data in a string, parse it and return an object (array) with member attributes that can be accessed from the main class. I've read that this is a better solution than having multiple indexed arrays like pointx[], pointy[], pointz[], etc.., especially if you need to perform operations like swapping or sorting.
So, I'd like to access the array object's members from main with something like test[0].x, test[100].y, etc. however, I'm frustratingly getting an Exception in thread "main" java.lang.NullPointerException and I don't understand how to proceed.
Here's how I'm calling parse from main:
parse a = new parse();
parse[] test = a.convert("1 2 3 4 1 2 3 4 1 2 3 4"); // <- ** error here **
System.out.printf("%.2f %.2f %.2f %d\n", test[0].x, test[0].y, test[0].z, test[0].r);
Here's the parse class:
public class parse {
parse[] point = new parse[1000];
public float x;
public float y;
public float z;
public int r;
parse() {
}
public parse[] convert(String vertices) {
// parse string vertices -> object
point[0].x = 10; // <- ** error here **
point[0].y = 100;
point[0].z = 50;
point[0].r = 5;
return point;
}
}
Thanks in advance for any help specifically with my parse class & any related java pointers to continue my learning java and enjoyment of programming!
When you create an array of parse objects the array itself is empty and doesn't actually contain any objects, only null references. You also need to create the objects themselves and store them in the array.
Furthermore, your point is a member of your parse class when it should be a local variable of your convert method, which itself should be static, since it doesn't rely on a particular instance.
You would then invoke the conversion as follows:
parse[] test = parse.convert("this string not used yet");
System.out.printf("%.2f %.2f %.2f %d\n", test[0].x, test[0].y, test[0].z, test[0].r);
Here's the parse class:
public class parse {
public float x;
public float y;
public float z;
public int r;
parse() {
}
public static parse[] convert(String vertices) {
// parse string vertices -> object
parse[] point = new parse[1000];
point[0] = new parse();
point[0].x = 10;
point[0].y = 100;
point[0].z = 50;
point[0].r = 5;
return point;
}
}

Dynamic array of an object

Maybe the solution is very simple. It must be, but maybe I am overlooking something
I have:
public class Object {
public int pos_x;
public int pos_y;
}
Object testObject[] = new object[10]
and then somewhere in a function
testObject[1].pos_x = 1;
It force closes my app.. how? and why? What can be the cause of this.
Furthermore. Ideally I would need something like this
testObject[].add_new_object();
testobject[].remove_item(3);
can this be done?
Thank you for helping
You have allocated an array that can hold 10 objects.
You also need to allocate the objects.
I'm not sure about the language you are using - if C# you cannot use 'Object' as the class name.
First creating a custom object (the 'object' data type):
public class MyObject {
public int pos_x;
public int pos_y;
}
...fair enough, a very basic class that holds coordinates. Next you want to create an array of MyObject. To do that, you declare your array type as MyObject[] and provide an optional size:
MyObject[] myObjArray = new MyObject[10]; // this gives a zero-based array of 10 elements, from 0-9
Now, you have the task of filling the array. The most common method would be to use a counter variable that counts from 0 to 9, the same elements we have in our array:
for (int i=0; i<=9; i++)
{
myObjArray[i] = new MyObject();
// you can also assign the variables' values here
myObjArray[i].pos_x = GetNextXVal(); // get the X value from somewhere
myObjArray[i].pos_y = GetNextYVal(); // get the y value from somewhere
}
Depending on your language, I'm sure we can point you to some good tutorials, books, or other references to help you get started.
Happy coding!

Resources