如何将List <CustomClass>转换为ArrayList <CustomClass>,反之亦然?

Bha*_*hta -2 java android list arraylist sharedpreferences

我有一个CustomClass,Bean/Model/Pojo它用于从Json保存自定义Obejcts.我希望保存ArrayListCustomClass的内容SharedPreference并在特殊情况下将其恢复.我发现它存储在一个方式SharedPreference 在这里!正确的答案是SpyZip 我能够存储和检索一个,List但我想存储和检索一个ArrayList.

这是一个片段,显示我如何存储和检索值SharedPreference:

    // This method will save custom class ArrayList<Bean>
    public void saveUserFavouriteStations(
            ArrayList<RadioStationBean> radioStation) {
        FavouriteStationHolder = this.getSharedPreferences("stations", 0);
        Editor editor = FavouriteStationHolder.edit();
        Gson gson = new Gson();
        String jsonCars = gson.toJson(radioStation);
        editor.putString("stations", jsonCars);
        System.out.println("Custom ArrayList Saved in App Class");
        editor.commit();
    }

    public ArrayList<RadioStationBean> getUserFavouriteStations() {
        FavouriteStationHolder = this.getSharedPreferences("stations", 0);
        if (FavouriteStationHolder != null) {
            String jsonString = FavouriteStationHolder
                    .getString("stations", "");
            Type type = new TypeToken<List<RadioStationBean>>() {
            }.getType();
            List<RadioStationBean> carsList = gson.fromJson(jsonString, type);
            return carsList;
        } else {

            return null;
        }
    } 
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 6

ArrayList是接口的特定(基于数组)实现List.由于您应该很少关心底层实现,并且这似乎不是极少数情况之一,只需更改方法签名以List在参数列表和返回值中使用.