Domanda

I'm looking for an efficient way to do this. Assume I have two Array with object Point.

Point[] a1 = {/*something that is Point*/}
Point[] a2 = {/*something that is Point*/}

And what I want is get the mutual things in two arrays without using java.util.*

for example

Point[] a1 = {Point1, Point2, Point3}
Point[] a2 = {Point2, Point3}

I want to get an new array a3 that is

a3 = {Point2, Point3} 

The things that confuse me is, I have no idea how long a3 will be. So do I have to loop through both a1, a2 to count how many mutual items there, and

Point[] a3 = new Point[count]

Then loop through the a1, a2 again and put items in?? This looks pretty inefficient. Are there more elegant ways to do it, as this may come up all the time.

È stato utile?

Soluzione

Because arrays are not re-sizable, what you can do is make an array that has a size equal to the size of the smallest of the two other arrays.

Keep an index for that array and add common elements as you loop through both arrays.

When you are done, create a new array with a size equal to the index you've reached and copy them over.

But, honestly, use java.util.* or some other library like Guava.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top