标签: arraylist

尝试从ArrayList中的字符串中删除特定单词

我正在制作一个ArrayList需要Strings,并且该类中的一个方法需要a String,在其前面加上"urgent:",并将其放在列表的开头.我现在正在编写一种方法,该方法应该采用a int,a String的位置,并将该字符串"降级"到列表的末尾.

但是,如果字符串前面有"urgent:",那么该方法也应该删除"urgent:"如果它被降级.一切都编译并运行,但它并没有删除"紧急:",我不知道为什么.

public void addUrgetItem(String newItem) {
    String urgentItem = newItem; 
    items.add(0, "urgent: " + urgentItem); 
}

public void demote(int position) {
    int size = items.size();  
    String itemAtSpot = items.get(position); 
    items.remove(itemAtSpot); 
    items.add((size-1), itemAtSpot); 

    if (itemAtSpot.startsWith("urgent:")) {
        items.remove("urgent:"); 
    }
}
Run Code Online (Sandbox Code Playgroud)

java arraylist

0
推荐指数
1
解决办法
353
查看次数

Java - 在Hashmap <Class,ArrayList <Class >>中返回具有最长ArrayList的键

我一直在尝试从类似问题的顶部答案中修改代码,但我不能让它适用于arraylist长度

从hashmap获取具有最大值的键?

可以说我有

HashMap<Customer,ArrayList<Call>> outgoingCalls = new HashMap<Customer,ArrayList<Call>>();

程序运行时,它会存储在hashmap中进行的每个调用.我想运行这个hashmap并返回拨打过多电话的客户.我一直试图从上面的链接修改这个代码,但我完全迷失了

   Entry<Customer,ArrayList<Call> mostCalls = null;

   for(Entry<String,ArrayList<Call> e : outgoingCalls.entrySet()) {
     if (mostCalls == null || e.getValue() > mostCalls.getValue()) {
        mostCalls = e;
Run Code Online (Sandbox Code Playgroud)

java arraylist hashmap

0
推荐指数
1
解决办法
107
查看次数

Java:ArraryList,如何计算具有相同实例变量的元素数量?

上下文:尝试编写将存储音乐专辑的程序.

所以我创建了一个名为'Album'的对象,默认构造函数如下:

public Album(String artist, String title, int trackCount){
    this.artist = artist;
    this.title = title;
    this trackCount = trackCount
    status = null
}
Run Code Online (Sandbox Code Playgroud)

变量status指的是3种可能的状态:

可用; 破碎; 失踪.

然后我做了一个arraylist:

...
public class AlbumList(){
    albumList = new ArrayList<Album>();
}
Run Code Online (Sandbox Code Playgroud)

我知道该.size()方法将返回列表中的元素数量.

但是我不确定如何找到列表中缺少的专辑数量.

我在想我应该创建一个变量,比如int missingAlbums,然后从这里可以使用if语句来遍历数组并在missingAlbums每次找到状态为MISSING的相册时递增.虽然我不完全确定如何做到这一点.

这是我的代码:

public int numberOfMissingAlbums(){
    missingAlbums= 0;
    for(Album missingRecord: AlbumList){
        if(missingRecord.status.equals("MISSING")){
            missingAlbums++;
        }
    }
    return missingAlbums;
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,上面写着".不兼容类型的.equals",我不知道问题是什么.

任何帮助表示赞赏.

java arraylist count

0
推荐指数
1
解决办法
191
查看次数

如何展平数组并摆脱空?

我试图采取任意深度嵌套的数组并展平数组,以及摆脱数组中的任何空对象.

例如,我希望能够输入一个嵌套数组, [1, 5, [[6, 4], 91, 12, null, [[null]]], -2] 并返回一个没有任何空值的一维数组.我该如何解决这个问题?

我在下面提供了我的解决方案,但我一直在寻找

我无法转换为java.lang.Integer错误.

public static void main(String[] args) {
    int[][] numbers = {null, {4, 5, 6},{3, 1, 10}, {4, 2, 9}, null, null};
    flatten(numbers);
}

public static ArrayList<Integer> flatten(Object[] nestedNumbers) {
    if (nestedNumbers == null) return null;
    ArrayList<Integer> flattenedNumbers = new ArrayList<>();
    for (Object element : nestedNumbers) {
        if (element != null) {
            flattenedNumbers.add((Integer)element);
        } 
    }
    return flattenedNumbers;
 }
Run Code Online (Sandbox Code Playgroud)

java arrays null arraylist object

0
推荐指数
1
解决办法
1309
查看次数

反序列化后,Object ArrayList会丢失String值吗?

所以我有一个三级视频商店GUI,它应该保存库存视频的记录.然而,它使用序列化保存视频对象,但由于某种原因,即使我没有得到任何错误,只有数值正在通过..

在此输入图像描述

注意最左边的三列和最右边的列是如何都是空的.这是因为它们意味着在它们中有字符串,但它们不...

正如我所说,我没有得到任何错误,所以这真的让我困惑.

VideoStore.java的构造函数(GUI类):

public VideoStore() {
        initComponents();
        model = (DefaultTableModel)displayVideos.getModel();
        try{
        BinaryFile = new BinaryFile();
        BinaryFile.load();
        }
        catch(Exception e){

        }
            for(int j = 1; j < BinaryFile.videosList.size(); j ++) {
            Video load = (Video)BinaryFile.videosList.get(j);
            String tempName = load.getVideoName();
            String tempProd = load.getProducer();
            String tempRat = load.getRating();
            String tempGenre = load.getGenre();
            short tempNum = load.getVidNum();
            float tempPrice = load.getvideoPrice(); 

            try {
                Object[] row = {ID, tempName, tempProd, tempGenre, tempPrice, tempNum, tempRat};
                model.addRow(row);
            } catch(Exception e){

            }

            ID++;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后我用来处理.ser文件的BinaryFile类: …

java serialization arraylist

0
推荐指数
1
解决办法
280
查看次数

如何减少未使用的ArrayList容量

在一些转换ArrayList有3个元素后,ArrayList大小最大然后是3.因此NullPointerException在使用forEachcircle 时会发生.

如何避免这种情况?我的意思是不!=null检查.

例:

List<String> busesIdToRemove = driverWrapper.getBusesIdToRemove(); 
Run Code Online (Sandbox Code Playgroud)

列表包含id的那些实体,将被删除.发生错误:

for (String id : busesIdToRemove) { 
Long longId = Long.valueOf(id); //here. Because id is null ... 
} 
Run Code Online (Sandbox Code Playgroud)

但实际上,list只包含非空值的元素.

例如[index,value].

1,"41";

4,"50"......

有关索引[0],[2],[3]的元素的信息在调试器中不存在,并且对于get(0)例如方法返回null .

解决问题:arrayList.removeAll(Collections.singleton(null));

java arraylist nullpointerexception

0
推荐指数
1
解决办法
89
查看次数

使用参数添加到类对象的ArrayList?

我有一个构造函数:

Candidate(String name, int numVotes)
{
    this.name = name;
    this.numVotes = numVotes;
}
Run Code Online (Sandbox Code Playgroud)

我已经制作了该类的ArrayList:

List <Candidate> election = new ArrayList<Candidate>();
Run Code Online (Sandbox Code Playgroud)

我正在尝试将此类的多个对象添加到ArrayList.我试过这个,但它不起作用:

election.add("John Smith", 5000);
election.add("Mary Miller", 4000);
Run Code Online (Sandbox Code Playgroud)

它抛出一个编译器错误说明:

The method add(int, Candidate) in the type List<Candidate> is not applicable for the arguments (String, int)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?任何帮助,将不胜感激.

java arraylist

0
推荐指数
1
解决办法
62
查看次数

添加元素后ArrayList为空

我有这个android代码,它从服务器中获取一个JSON并从该JSON填充一个ArrayList,我在onresponse空隙内检查了ArrayList“ meals”的大小,它给了我1,但是当我在StringRequest对象后对其进行检查时,我得到了0个项目。进餐在全局范围内定义,并在oncreateview函数内部进行初始化代码:

               public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i("debug","on create view");
View view =inflater.inflate(R.layout.fragment_meal_list,container,false);
ListView List ;
meals=new ArrayList<meal>();
String url="http://syriankitchen.tk/get_recent.php";
StringRequest mealsrequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

    @Override
    public void onResponse(String response) {
        try{
            JSONObject object= new JSONObject(response);
            JSONArray mealsArray = object.getJSONArray("result");
            for(int i=0;i<mealsArray.length();i++){
                JSONObject cur = mealsArray.getJSONObject(i);
                int id= cur.getInt("id");
                String name= cur.getString("name");
                String description = cur.getString("description");
                int price = cur.getInt("price");
                meals.add(new meal(id,name,price,description));
            }
            Log.i("debug","meals size …
Run Code Online (Sandbox Code Playgroud)

java android arraylist

0
推荐指数
1
解决办法
1224
查看次数

ArrayList删除方法不起作用?

这可能是重复的,但我看不出有任何关于此错误的问题,所以请道歉.

我正在尝试使用该remove()方法从我的移除整数ArrayList,但它给了我java.lang.UnsupportedOperationException.remove方法应该int对我的理解采用一个或整数,或者来自的值ArrayList,但这些似乎不起作用并给出相同的错误.

我也尝试使用"深度"作为index,因为这是index我想删除的.

这是我的代码:

import java.util.*;

public class EP{
public static List<Integer> items = Arrays.asList(12, 13, 48, 42, 38,     2827, 827, 828, 420);
public static void main(String[]args){
System.out.println("Exam List");
for(Integer i: items){
    System.out.println(i);
}
    Scanner scan = new Scanner(System.in);
System.out.println("Enter depth");
int depth = scan.nextInt();
System.out.println("Enter value");
int value = scan.nextInt();
System.out.println(mark(depth, value));
}

public static int  mark(int depth, int value){
int ret = -1; //This …
Run Code Online (Sandbox Code Playgroud)

java methods int integer arraylist

0
推荐指数
1
解决办法
318
查看次数

添加到ArrayList时发生NullPointerException [long post]

我正在为类项目创建一个正则表达式解析器,我遇到了一个我无法弄清楚如何修复的问题.每当遇到带括号的组时,都应该在groupsArrayList中添加一个占位符,然后可以从String中捕获一个组.问题是它每次尝试添加到此ArrayList时都会抛出NullPointerException.这是Segment构造函数,发生这种情况:

public Segment(String value, boolean capture) throws ParseException {
    values = new ArrayList<>();
    parse(value);
    minimum = 1;
    maximum = 1;
    matchNot = false;
    captureGroup = capture;
    if (capture) {
        RegexGUI.input.groups.add(""); //error occurs on this line
    }
}
Run Code Online (Sandbox Code Playgroud)

注意,RegexGUI.input指的是Regex构造函数所在的相关实例:

public Regex(String value) throws ParseException {
    this.value = value;
    segments = new ArrayList<>();
    groups = new ArrayList<>();
    anchorStart = false;
    anchorEnd = false;
    tokenize(value, true, false);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,groups在构造函数中显然已初始化.此外,Segment构造函数仅在类的tokenize()方法中调用 …

java arraylist nullpointerexception

0
推荐指数
1
解决办法
113
查看次数