android+list+insert,List

本文通过示例展示了如何在泛型列表(List<T>)中插入元素到指定索引、检查列表是否包含特定项以及插入和删除元素。文章详细解释了插入方法的工作原理,并给出了在不同编程语言中实现这些操作的代码片段,包括C#、VB.NET和F#。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

將項目插入至 List 中指定的索引位置。Inserts an element into the List at the specified index.

public:

virtual void Insert(int index, T item);

public void Insert (int index, T item);

abstract member Insert : int * 'T -> unit

override this.Insert : int * 'T -> unit

Public Sub Insert (index As Integer, item As T)

參數

index

應在 item 插入以零為起始的索引。The zero-based index at which item should be inserted.

item

T

要插入的物件。The object to insert. 參考類型的值可以是 null。The value can be null for reference types.

實作

例外狀況

index 小於 0。index is less than 0.

-或--or-

index 大於 Count。index is greater than Count.

範例

下列範例示範如何在中加入、移除和插入簡單的商務物件 List 。The following example demonstrates how to add, remove, and insert a simple business object in a List.

using System;

using System.Collections.Generic;

// Simple business object. A PartId is used to identify the type of part

// but the part name can change.

public class Part : IEquatable

{

public string PartName { get; set; }

public int PartId { get; set; }

public override string ToString()

{

return "ID: " + PartId + " Name: " + PartName;

}

public override bool Equals(object obj)

{

if (obj == null) return false;

Part objAsPart = obj as Part;

if (objAsPart == null) return false;

else return Equals(objAsPart);

}

public override int GetHashCode()

{

return PartId;

}

public bool Equals(Part other)

{

if (other == null) return false;

return (this.PartId.Equals(other.PartId));

}

// Should also override == and != operators.

}

public class Example

{

public static void Main()

{

// Create a list of parts.

List parts = new List();

// Add parts to the list.

parts.Add(new Part() {PartName="crank arm", PartId=1234});

parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });

parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });

parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });

parts.Add(new Part() { PartName = "cassette", PartId = 1534 });

parts.Add(new Part() { PartName = "shift lever", PartId = 1634 });

// Write out the parts in the list. This will call the overridden ToString method

// in the Part class.

Console.WriteLine();

foreach (Part aPart in parts)

{

Console.WriteLine(aPart);

}

// Check the list for part #1734. This calls the IEquatable.Equals method

// of the Part class, which checks the PartId for equality.

Console.WriteLine("\nContains(\"1734\"): {0}",

parts.Contains(new Part {PartId=1734, PartName="" }));

// Insert a new item at position 2.

Console.WriteLine("\nInsert(2, \"1834\")");

parts.Insert(2, new Part() { PartName = "brake lever", PartId = 1834 });

//Console.WriteLine();

foreach (Part aPart in parts)

{

Console.WriteLine(aPart);

}

Console.WriteLine("\nParts[3]: {0}", parts[3]);

Console.WriteLine("\nRemove(\"1534\")");

// This will remove part 1534 even though the PartName is different,

// because the Equals method only checks PartId for equality.

parts.Remove(new Part(){PartId=1534, PartName="cogs"});

Console.WriteLine();

foreach (Part aPart in parts)

{

Console.WriteLine(aPart);

}

Console.WriteLine("\nRemoveAt(3)");

// This will remove the part at index 3.

parts.RemoveAt(3);

Console.WriteLine();

foreach (Part aPart in parts)

{

Console.WriteLine(aPart);

}

/*

ID: 1234 Name: crank arm

ID: 1334 Name: chain ring

ID: 1434 Name: regular seat

ID: 1444 Name: banana seat

ID: 1534 Name: cassette

ID: 1634 Name: shift lever

Contains("1734"): False

Insert(2, "1834")

ID: 1234 Name: crank arm

ID: 1334 Name: chain ring

ID: 1834 Name: brake lever

ID: 1434 Name: regular seat

ID: 1444 Name: banana seat

ID: 1534 Name: cassette

ID: 1634 Name: shift lever

Parts[3]: ID: 1434 Name: regular seat

Remove("1534")

ID: 1234 Name: crank arm

ID: 1334 Name: chain ring

ID: 1834 Name: brake lever

ID: 1434 Name: regular seat

ID: 1444 Name: banana seat

ID: 1634 Name: shift lever

RemoveAt(3)

ID: 1234 Name: crank arm

ID: 1334 Name: chain ring

ID: 1834 Name: brake lever

ID: 1444 Name: banana seat

ID: 1634 Name: shift lever

*/

}

}

Imports System.Collections.Generic

' Simple business object. A PartId is used to identify the type of part

' but the part name can change.

Public Class Part

Implements IEquatable(Of Part)

Public Property PartName() As String

Get

Return m_PartName

End Get

Set(value As String)

m_PartName = Value

End Set

End Property

Private m_PartName As String

Public Property PartId() As Integer

Get

Return m_PartId

End Get

Set(value As Integer)

m_PartId = Value

End Set

End Property

Private m_PartId As Integer

Public Overrides Function ToString() As String

Return "ID: " & PartId & " Name: " & PartName

End Function

Public Overrides Function Equals(obj As Object) As Boolean

If obj Is Nothing Then

Return False

End If

Dim objAsPart As Part = TryCast(obj, Part)

If objAsPart Is Nothing Then

Return False

Else

Return Equals(objAsPart)

End If

End Function

Public Overrides Function GetHashCode() As Integer

Return PartId

End Function

Public Overloads Function Equals(other As Part) As Boolean _

Implements IEquatable(Of Part).Equals

If other Is Nothing Then

Return False

End If

Return (Me.PartId.Equals(other.PartId))

End Function

' Should also override == and != operators.

End Class

Public Class Example

Public Shared Sub Main()

' Create a list of parts.

Dim parts As New List(Of Part)()

' Add parts to the list.

parts.Add(New Part() With { _

.PartName = "crank arm", _

.PartId = 1234 _

})

parts.Add(New Part() With { _

.PartName = "chain ring", _

.PartId = 1334 _

})

parts.Add(New Part() With { _

.PartName = "regular seat", _

.PartId = 1434 _

})

parts.Add(New Part() With { _

.PartName = "banana seat", _

.PartId = 1444 _

})

parts.Add(New Part() With { _

.PartName = "cassette", _

.PartId = 1534 _

})

parts.Add(New Part() With { _

.PartName = "shift lever", _

.PartId = 1634 _

})

' Write out the parts in the list. This will call the overridden ToString method

' in the Part class.

Console.WriteLine()

For Each aPart As Part In parts

Console.WriteLine(aPart)

Next

' Check the list for part #1734. This calls the IEquatable.Equals method

' of the Part class, which checks the PartId for equality.

Console.WriteLine(vbLf & "Contains(""1734""): {0}", parts.Contains(New Part() With { _

.PartId = 1734, _

.PartName = "" _

}))

' Insert a new item at position 2.

Console.WriteLine(vbLf & "Insert(2, ""1834"")")

parts.Insert(2, New Part() With { _

.PartName = "brake lever", _

.PartId = 1834 _

})

'Console.WriteLine();

For Each aPart As Part In parts

Console.WriteLine(aPart)

Next

Console.WriteLine(vbLf & "Parts[3]: {0}", parts(3))

Console.WriteLine(vbLf & "Remove(""1534"")")

' This will remove part 1534 even though the PartName is different,

' because the Equals method only checks PartId for equality.

parts.Remove(New Part() With { _

.PartId = 1534, _

.PartName = "cogs" _

})

Console.WriteLine()

For Each aPart As Part In parts

Console.WriteLine(aPart)

Next

Console.WriteLine(vbLf & "RemoveAt(3)")

' This will remove part at index 3.

parts.RemoveAt(3)

Console.WriteLine()

For Each aPart As Part In parts

Console.WriteLine(aPart)

Next

End Sub

'

' This example code produces the following output:

' ID: 1234 Name: crank arm

' ID: 1334 Name: chain ring

' ID: 1434 Name: regular seat

' ID: 1444 Name: banana seat

' ID: 1534 Name: cassette

' ID: 1634 Name: shift lever

'

' Contains("1734"): False

'

' Insert(2, "1834")

' ID: 1234 Name: crank arm

' ID: 1334 Name: chain ring

' ID: 1834 Name: brake lever

' ID: 1434 Name: regular seat

' ID: 1444 Name: banana seat

' ID: 1534 Name: cassette

' ID: 1634 Name: shift lever

'

' Parts[3]: ID: 1434 Name: regular seat

'

' Remove("1534")

'

' ID: 1234 Name: crank arm

' ID: 1334 Name: chain ring

' ID: 1834 Name: brake lever

' ID: 1434 Name: regular seat

' ID: 1444 Name: banana seat

' ID: 1634 Name: shift lever

' '

' RemoveAt(3)

'

' ID: 1234 Name: crank arm

' ID: 1334 Name: chain ring

' ID: 1834 Name: brake lever

' ID: 1444 Name: banana seat

' ID: 1634 Name: shift lever

'

End Class

// Simple business object. A PartId is used to identify the type of part

// but the part name can change.

[]

type Part = { PartId : int ; mutable PartName : string } with

override this.GetHashCode() = hash this.PartId

override this.Equals(other) =

match other with

| :? Part as p -> this.PartId = p.PartId

| _ -> false

override this.ToString() = sprintf "ID: %i Name: %s" this.PartId this.PartName

[]

let main argv =

// We refer to System.Collections.Generic.List by its type

// abbreviation ResizeArray to avoid conflicts with the F# List module.

// Note: In F# code, F# linked lists are usually preferred over

// ResizeArray when an extendable collection is required.

let parts = ResizeArray<_>()

parts.Add({PartName = "crank arm" ; PartId = 1234})

parts.Add({PartName = "chain ring"; PartId = 1334 })

parts.Add({PartName = "regular seat"; PartId = 1434 })

parts.Add({PartName = "banana seat"; PartId = 1444 })

parts.Add({PartName = "cassette"; PartId = 1534 })

parts.Add({PartName = "shift lever"; PartId = 1634 })

// Write out the parts in the ResizeArray. This will call the overridden ToString method

// in the Part type

printfn ""

parts |> Seq.iter (fun p -> printfn "%O" p)

// Check the ResizeArray for part #1734. This calls the IEquatable.Equals method

// of the Part type, which checks the PartId for equality.

printfn "\nContains(\"1734\"): %b" (parts.Contains({PartId=1734; PartName=""}))

// Insert a new item at position 2.

printfn "\nInsert(2, \"1834\")"

parts.Insert(2, { PartName = "brake lever"; PartId = 1834 })

// Write out all parts

parts |> Seq.iter (fun p -> printfn "%O" p)

printfn "\nParts[3]: %O" parts.[3]

printfn "\nRemove(\"1534\")"

// This will remove part 1534 even though the PartName is different,

// because the Equals method only checks PartId for equality.

// Since Remove returns true or false, we need to ignore the result

parts.Remove({PartId=1534; PartName="cogs"}) |> ignore

// Write out all parts

printfn ""

parts |> Seq.iter (fun p -> printfn "%O" p)

printfn "\nRemoveAt(3)"

// This will remove the part at index 3.

parts.RemoveAt(3)

// Write out all parts

printfn ""

parts |> Seq.iter (fun p -> printfn "%O" p)

0 // return an integer exit code

下列範例示範 Insert 方法,以及泛型類別的各種其他屬性和方法 List 。The following example demonstrates the Insert method, along with various other properties and methods of the List generic class. 建立清單之後,就會加入元素。After the list is created, elements are added. Insert方法是用來將專案插入清單的中間。The Insert method is used to insert an item into the middle of the list. 插入的專案是重複的專案,稍後會使用方法來移除 Remove 。The item inserted is a duplicate, which is later removed using the Remove method.

using namespace System;

using namespace System::Collections::Generic;

void main()

{

List^ dinosaurs = gcnew List();

Console::WriteLine("\nCapacity: {0}", dinosaurs->Capacity);

dinosaurs->Add("Tyrannosaurus");

dinosaurs->Add("Amargasaurus");

dinosaurs->Add("Mamenchisaurus");

dinosaurs->Add("Deinonychus");

dinosaurs->Add("Compsognathus");

Console::WriteLine();

for each(String^ dinosaur in dinosaurs )

{

Console::WriteLine(dinosaur);

}

Console::WriteLine("\nCapacity: {0}", dinosaurs->Capacity);

Console::WriteLine("Count: {0}", dinosaurs->Count);

Console::WriteLine("\nContains(\"Deinonychus\"): {0}",

dinosaurs->Contains("Deinonychus"));

Console::WriteLine("\nInsert(2, \"Compsognathus\")");

dinosaurs->Insert(2, "Compsognathus");

Console::WriteLine();

for each(String^ dinosaur in dinosaurs )

{

Console::WriteLine(dinosaur);

}

Console::WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

Console::WriteLine("\nRemove(\"Compsognathus\")");

dinosaurs->Remove("Compsognathus");

Console::WriteLine();

for each(String^ dinosaur in dinosaurs )

{

Console::WriteLine(dinosaur);

}

dinosaurs->TrimExcess();

Console::WriteLine("\nTrimExcess()");

Console::WriteLine("Capacity: {0}", dinosaurs->Capacity);

Console::WriteLine("Count: {0}", dinosaurs->Count);

dinosaurs->Clear();

Console::WriteLine("\nClear()");

Console::WriteLine("Capacity: {0}", dinosaurs->Capacity);

Console::WriteLine("Count: {0}", dinosaurs->Count);

}

/* This code example produces the following output:

Capacity: 0

Tyrannosaurus

Amargasaurus

Mamenchisaurus

Deinonychus

Compsognathus

Capacity: 8

Count: 5

Contains("Deinonychus"): True

Insert(2, "Compsognathus")

Tyrannosaurus

Amargasaurus

Compsognathus

Mamenchisaurus

Deinonychus

Compsognathus

dinosaurs[3]: Mamenchisaurus

Remove("Compsognathus")

Tyrannosaurus

Amargasaurus

Mamenchisaurus

Deinonychus

Compsognathus

TrimExcess()

Capacity: 5

Count: 5

Clear()

Capacity: 5

Count: 0

*/

List dinosaurs = new List();

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

dinosaurs.Add("Tyrannosaurus");

dinosaurs.Add("Amargasaurus");

dinosaurs.Add("Mamenchisaurus");

dinosaurs.Add("Deinonychus");

dinosaurs.Add("Compsognathus");

Console.WriteLine();

foreach(string dinosaur in dinosaurs)

{

Console.WriteLine(dinosaur);

}

Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);

Console.WriteLine("Count: {0}", dinosaurs.Count);

Console.WriteLine("\nContains(\"Deinonychus\"): {0}",

dinosaurs.Contains("Deinonychus"));

Console.WriteLine("\nInsert(2, \"Compsognathus\")");

dinosaurs.Insert(2, "Compsognathus");

Console.WriteLine();

foreach(string dinosaur in dinosaurs)

{

Console.WriteLine(dinosaur);

}

// Shows accessing the list using the Item property.

Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);

Console.WriteLine("\nRemove(\"Compsognathus\")");

dinosaurs.Remove("Compsognathus");

Console.WriteLine();

foreach(string dinosaur in dinosaurs)

{

Console.WriteLine(dinosaur);

}

dinosaurs.TrimExcess();

Console.WriteLine("\nTrimExcess()");

Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);

Console.WriteLine("Count: {0}", dinosaurs.Count);

dinosaurs.Clear();

Console.WriteLine("\nClear()");

Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);

Console.WriteLine("Count: {0}", dinosaurs.Count);

/* This code example produces the following output:

Capacity: 0

Tyrannosaurus

Amargasaurus

Mamenchisaurus

Deinonychus

Compsognathus

Capacity: 8

Count: 5

Contains("Deinonychus"): True

Insert(2, "Compsognathus")

Tyrannosaurus

Amargasaurus

Compsognathus

Mamenchisaurus

Deinonychus

Compsognathus

dinosaurs[3]: Mamenchisaurus

Remove("Compsognathus")

Tyrannosaurus

Amargasaurus

Mamenchisaurus

Deinonychus

Compsognathus

TrimExcess()

Capacity: 5

Count: 5

Clear()

Capacity: 5

Count: 0

*/

Imports System.Collections.Generic

Public Class Example

Public Shared Sub Main()

Dim dinosaurs As New List(Of String)

Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)

dinosaurs.Add("Tyrannosaurus")

dinosaurs.Add("Amargasaurus")

dinosaurs.Add("Mamenchisaurus")

dinosaurs.Add("Deinonychus")

dinosaurs.Add("Compsognathus")

Console.WriteLine()

For Each dinosaur As String In dinosaurs

Console.WriteLine(dinosaur)

Next

Console.WriteLine(vbLf & "Capacity: {0}", dinosaurs.Capacity)

Console.WriteLine("Count: {0}", dinosaurs.Count)

Console.WriteLine(vbLf & "Contains(""Deinonychus""): {0}", _

dinosaurs.Contains("Deinonychus"))

Console.WriteLine(vbLf & "Insert(2, ""Compsognathus"")")

dinosaurs.Insert(2, "Compsognathus")

Console.WriteLine()

For Each dinosaur As String In dinosaurs

Console.WriteLine(dinosaur)

Next

' Shows how to access the list using the Item property.

Console.WriteLine(vbLf & "dinosaurs(3): {0}", dinosaurs(3))

Console.WriteLine(vbLf & "Remove(""Compsognathus"")")

dinosaurs.Remove("Compsognathus")

Console.WriteLine()

For Each dinosaur As String In dinosaurs

Console.WriteLine(dinosaur)

Next

dinosaurs.TrimExcess()

Console.WriteLine(vbLf & "TrimExcess()")

Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)

Console.WriteLine("Count: {0}", dinosaurs.Count)

dinosaurs.Clear()

Console.WriteLine(vbLf & "Clear()")

Console.WriteLine("Capacity: {0}", dinosaurs.Capacity)

Console.WriteLine("Count: {0}", dinosaurs.Count)

End Sub

End Class

' This code example produces the following output:

'

'Capacity: 0

'

'Tyrannosaurus

'Amargasaurus

'Mamenchisaurus

'Deinonychus

'Compsognathus

'

'Capacity: 8

'Count: 5

'

'Contains("Deinonychus"): True

'

'Insert(2, "Compsognathus")

'

'Tyrannosaurus

'Amargasaurus

'Compsognathus

'Mamenchisaurus

'Deinonychus

'Compsognathus

'

'dinosaurs(3): Mamenchisaurus

'

'Remove("Compsognathus")

'

'Tyrannosaurus

'Amargasaurus

'Mamenchisaurus

'Deinonychus

'Compsognathus

'

'TrimExcess()

'Capacity: 5

'Count: 5

'

'Clear()

'Capacity: 5

'Count: 0

[]

let main argv =

// We refer to System.Collections.Generic.List by its type

// abbreviation ResizeArray to avoid conflict with the List module.

// Note: In F# code, F# linked lists are usually preferred over

// ResizeArray when an extendable collection is required.

let dinosaurs = ResizeArray<_>()

// Write out the dinosaurs in the ResizeArray.

let printDinosaurs() =

printfn ""

dinosaurs |> Seq.iter (fun p -> printfn "%O" p)

printfn "\nCapacity: %i" dinosaurs.Capacity

dinosaurs.Add("Tyrannosaurus")

dinosaurs.Add("Amargasaurus")

dinosaurs.Add("Mamenchisaurus")

dinosaurs.Add("Deinonychus")

dinosaurs.Add("Compsognathus")

printDinosaurs()

printfn "\nCapacity: %i" dinosaurs.Capacity

printfn "Count: %i" dinosaurs.Count

printfn "\nContains(\"Deinonychus\"): %b" (dinosaurs.Contains("Deinonychus"))

printfn "\nInsert(2, \"Compsognathus\")"

dinosaurs.Insert(2, "Compsognathus")

printDinosaurs()

// Shows accessing the list using the Item property.

printfn "\ndinosaurs[3]: %s" dinosaurs.[3]

printfn "\nRemove(\"Compsognathus\")"

dinosaurs.Remove("Compsognathus") |> ignore

printDinosaurs()

dinosaurs.TrimExcess()

printfn "\nTrimExcess()"

printfn "Capacity: %i" dinosaurs.Capacity

printfn "Count: %i" dinosaurs.Count

dinosaurs.Clear()

printfn "\nClear()"

printfn "Capacity: %i" dinosaurs.Capacity

printfn "Count: %i" dinosaurs.Count

0 // return an integer exit code

(* This code example produces the following output:

Capacity: 0

Tyrannosaurus

Amargasaurus

Mamenchisaurus

Deinonychus

Compsognathus

Capacity: 8

Count: 5

Contains("Deinonychus"): true

Insert(2, "Compsognathus")

Tyrannosaurus

Amargasaurus

Compsognathus

Mamenchisaurus

Deinonychus

Compsognathus

dinosaurs[3]: Mamenchisaurus

Remove("Compsognathus")

Tyrannosaurus

Amargasaurus

Mamenchisaurus

Deinonychus

Compsognathus

TrimExcess()

Capacity: 5

Count: 5

Clear()

Capacity: 5

Count: 0

*)

備註

List 接受 null 做為參考型別的有效值,並允許重複的專案。List accepts null as a valid value for reference types and allows duplicate elements.

如果 Count 已等於 Capacity ,的容量會藉 List 由自動重新配置內部陣列來增加,而且現有的元素會在加入新元素之前複製到新的陣列。If Count already equals Capacity, the capacity of the List is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.

如果 index 等於 Count , item 則會新增至的結尾 List 。If index is equal to Count, item is added to the end of List.

此方法是 O (n) 作業,其中 n 為 Count 。This method is an O(n) operation, where n is Count.

適用於

另請參閱

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值