Question

I am new to both Java and Android so hopefully my question will make sense (I think I know what I am asking!)

I am working my way through an example in a book and I have a query with the following statement:

String[] tags = savedSearches.getAll().keySet().toArray(new String[0]);

Where savedSearches is a SharedPreferences Object.

savedSearches.getAll() returns a Map which allows the call to KeySet() to be made. What I am failing to understand is how the KeySet() call is possible. I am under the impression that if you are going to be using a class/Interface in your code then you need to import it or import a class/Interface which directly or Indirectly extends/implements the object making the call, in this case a reference to a Map.

The example I am working on imports the following:

import java.util.Arrays;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;

I have had a look at the Java and Android API and I can’t see that a Map is implemented in any of the above (unless I have missed it!) so in principle I should not be able to make a call to KeySet(). So how is it possible to make this call to KeySet()?

Hopefully the above will make some sort of sense :/ Any help or pointers in the right direction to help me understand this would be much appreciated.

Was it helpful?

Solution

keySet() is a method that returns a set of all the keys of the Map(public Set<K> keySet ()). So, methods are not to be imported. Though Map is not imported but the return type of getAll() method is Map<String, ?> so it can be directly accessed.

If you fetch getAll() seperately like,

Map<String, ?> map = preferences.getAll();

Then you will have Map imported else you can directly access it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top