首页 > 编程语言 >Java: ArrayList

Java: ArrayList

时间:2022-11-27 07:44:48浏览次数:55  
标签:Java cars ArrayList Ford Mazda add java

The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified. While elements can be added and removed from an ArrayList whenever you want.

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  }
}

// Outputs
[Volvo, BMW, Ford, Mazda]

Sort an ArrayList

import java.util.ArrayList;
import java.util.Collections;  // Import the Collections class

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    Collections.sort(cars);  // Sort cars

    System.out.println(i);
  }
}

// Outputs
[BMW, Ford, Mazda, Volvo]

 

标签:Java,cars,ArrayList,Ford,Mazda,add,java
From: https://www.cnblogs.com/ShengLiu/p/16928941.html

相关文章

  • Java: LinkedList
    The LinkedList classisalmostidenticaltothe ArrayList:importjava.util.LinkedList;publicclassMain{publicstaticvoidmain(String[]args){......
  • Java: Date and Time
    Javadoesnothaveabuilt-inDateclass,butwecanimportthe java.time packagetoworkwiththedateandtimeAPI.ClassDescriptionLocalDateRepresent......
  • Java: User Input (Scanner)
    The Scanner classisusedtogetuserinput,anditisfoundinthe java.util package.Tousethe Scanner class,createanobjectoftheclassandusean......
  • Java: Enums
    An enum isaspecial"class"thatrepresentsagroupof constants (unchangeablevariables,like final variables).enumLevel{LOW,MEDIUM,HIGH}......
  • Java: Interface
    Anotherwaytoachieve abstraction inJava,iswithinterfaces.An interface isacompletely"abstractclass"thatisusedtogrouprelatedmethodswithem......
  • Java: Inner Classes
    InJava,itisalsopossibletonestclasses(aclasswithinaclass).Thepurposeofnestedclassesistogroupclassesthatbelongtogether,whichmakesyour......
  • Java: Abstraction
    Abstractioncanbeachievedwitheither abstractclasses or interfaces.The abstract keywordisanon-accessmodifier,usedforclassesandmethods:Abst......
  • Java: Classes
    WhatareClassesandObjects?Aclassisatemplateforobjects,andanobjectisaninstanceofaclass.   Staticvs.Publicwecreateda static met......
  • Collectors groupingBy() method in Java with Examples
    https://www.geeksforgeeks.org/collectors-groupingby-method-in-java-with-examples/The groupingBy() methodofCollectorsclassinJavaareusedforgroupingo......
  • Java 8 | Collectors counting() with Examples
    https://www.geeksforgeeks.org/java-8-collectors-counting-with-examples/Collectorscounting() methodisusedtocountthenumberofelementspassedinthestr......