How to use vectors/arrays in Java?

Asked

Viewed 3,831 times

3

Hello, I am very layy in Java and need to use a variable storing several others. How can I do this? I have the following:

LatLng ponto1 = new LatLng(-19.924312,-43.931762);
LatLng ponto2 = new LatLng(-18.851388,-41.946910);

I’m used to C, where I could do something like:

LatLng pontos[2];
LatLng pontos[1] = new LatLng(-19.924312,-43.931762);
LatLng pontos[2] = new LatLng(-18.851388,-41.946910);

But when I try this in Android Studio, it returns me syntax errors... How would be the right way to do?

Note: I need to do this to compare several "points" within a "for", I think this is the best way...

--- EDIT ---

It returns me type errors:

  • Unkown class: points
  • Missing method body, or declare Abstract

--EDIT2-- (code, as Maniero requested)

public class Mapa extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mapa);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

LatLng ponto1 = new LatLng(-19.924312,-43.931762);
LatLng ponto2 = new LatLng(-18.851388,-41.946910);

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if (ActivityCompat.checkSelfPermission(Mapa.this,     android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Mapa.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(Mapa.this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }else{
        if(!mMap.isMyLocationEnabled())
            mMap.setMyLocationEnabled(true);

        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (myLocation == null) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String provider = lm.getBestProvider(criteria, true);
            myLocation = lm.getLastKnownLocation(provider);
        }

        if(myLocation!=null){
            LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14), 1500, null);
            double distancia = SphericalUtil.computeDistanceBetween(ponto1, userLocation);
            double valorLatitude = myLocation.getLatitude();
            double valorLongitude = myLocation.getLongitude();

            /*String stringLongitude = Double.toString(valorLongitude);
            String stringLatitude = Double.toString(valorLatitude);*/
            String stringDistancia = Double.toString(distancia);

            TextView textLatitude = (TextView) findViewById(R.id.textLatitude);
            textLatitude.setText(stringDistancia);
            /*TextView textLongitude = (TextView) findViewById(R.id.textLongitude);
            textLongitude.setText(stringLongitude);*/
        }
    }
}

I am using the 'Sphericalutil.computeDistanceBetween' function to calculate the distance from point 1 with the user’s position. This works normally, so... Now I needed a 'for' to calculate the distance of each point I list above in relation to the user’s position and then return me to the shortest distance... For this, I think I would need to put all the dots in a single array and test element by array element, but I don’t know how to declare the array up there...

  • 1

    And where’s the code? You can [Dit] the question and put it to us to analyze

  • Code added (:

  • With that alone you can’t tell, or maybe the mistake is just having this :)

  • Basically only this in my map class, I just stopped listing the Imports and the package hehe

  • I don’t understand your comparison to the C language...

  • It is that in the C language, I can declare an array, for example, of type int with 11 elements (starts counting from 0)... It would look something like: int array[10]; E, right after, I could access position element 5 using: array[5];

Show 1 more comment

2 answers

4

In java, learn that the base language is this, only the base, one of the great strengths of Java is its built-in libraries that do 1001 things, and it comes all pre-made in JDK.

An Array, the way you’re used to C would be:

Object[] array = new Object[10];

this creates an empty array of the type Object 10-point, empty ball. But in newer versions of java we have the 'shortcut':

String[] array = {"um elemento", "outro elemento"}

That initializes an array with size 2 and already with the two elements inside, the pattern can apply to any other type of variable. Numbers, objects:

{new LatLang(10.22, -2.44),new LatLang(1.22, -4.66)}  

etc... But in java 8 is much more common the more "modern" version of java sets Lists, Maps, Sets, ETC

The equivalent of arrays in our library of sets would be ArrayList, the difference is that sets are objects, have dynamic size and support various built-in operations: sort, take specific item, search, etc. They are part of the JDK and you can use:

ArrayList<Object> lista = new ArrayList(); 
// E para adicionar items:
lista.add(new Object());
// Voce pode ate especificar o indice
lista.add(3, new Object());
// Mas cuidado, as listas se por mais que listas se expandam sozinhas para 
// acomodar novos indices elas tem índice. o padrão inicial é 10
// voce nao pode acabar de criar uma lista e:
lista.add(10000, new Object());
  • Um... understood! But then, which would be more appropriate for what I need to do? Use this type of arrays, or lists as cited by friend J. Guilherme? And what are the main differences? If I’m not mistaken, in the case of the list, when you remove an element, the next element takes its position, something like?

  • Right, it will work perfectly with what I need! Thank you very much!

  • Happy to help. To access the built-ins that menceonei is list.metodo()

  • Top! saved me a lot of time, I was breaking my head with dynamic size arrays in Java, I’m very used to dynamic arrays of PHP language, I used your example in String format private ArrayList<String> mTrainingPath = new ArrayList();, worked perfectly... Thank you.

3

Create a list:

List<LatLng> pontos = new ArrayList<LatLng>();
pontos.add(new LatLng(-19.924312,-43.931762));
pontos.add(new LatLng(-18.851388,-41.946910));

Then recover by pontos.get(0), for example.

  • I think that’s exactly what I need, but when I add the 3 lines you said, Android Studio underlines in red the 'new List<Latlng>();' section and returns me the message 'List' is Abstract; cannot be instantied... What can it be?

  • In java, List is interface.. I didn’t know.. A concrete implementation of List is Arraylist.. see my edit

  • Ah, yes... I get it... Perfect then! It worked here... I really appreciate it!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.