Java StringBuilder sureCapacity()方法与示例

StringBuilder类sureCapacity()方法 (StringBuilder Class ensureCapacity() method)

  • ensureCapacity() method is available in java.lang package.

    sureCapacity()方法在java.lang包中可用。

  • ensureCapacity() method is used to check the ensurity of the capacity with the given capacity (i.e. we ensure that the capacity is equal to the given argument).

    guaranteeCapacity()方法用于检查具有给定容量的容量的安全性(即,我们确保容量等于给定参数)。

    In this method let suppose argument capacity > current capacity so in that case new space allocated for an array with larger capacity so the new capacity will be:

    在此方法中,假设参数容量>当前容量,因此在这种情况下,为具有较大容量的数组分配了新空间,因此新容量将为:

        New Capacity = New Capacity > min_cap
        New Capacity = 2*old Capacity +2
    
    Note: When we pass the negative value as an argument so in that case no action will perform and simply returns 注意:当我们将负值作为参数传递时,在这种情况下,将不会执行任何操作,只会返回
  • ensureCapacity() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.

    guaranteeCapacity()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。

  • ensureCapacity() method does not throw an exception at the time of the ensurity of the capacity.

    sureCapacity()方法在确保容量时不会引发异常。

Syntax:

句法:

    public void ensureCapacity(int min_cap);

Parameter(s):

参数:

  • int min_cap – represents the minimum capacity required to perform action.

    int min_cap –表示执行操作所需的最小容量。

Return value:

返回值:

The return type of this method is void, it returns nothing.

此方法的返回类型为void ,不返回任何内容。

Example:

例:

// Java program to demonstrate the example 
// of void ensureCapacity(int min_cap)
// method of StringBuilder 


public class EnsureCapacity {
    public static void main(String[] args) {
        // Creating an StringBuilder object
        StringBuilder st_b = new StringBuilder("Java World");

        // Display st_b
        System.out.println("st_b = " + st_b);

        // Display Current Capacity st_b i.e. 16+10
        System.out.println("st_b.capacity() = " + st_b.capacity());

        // By using ensureCapacity() method is to extend the capacity 
        // with the given amount to st_b object if required
        // it returns twice the old capacity + 2 i.e.(2*st_b+2)
        st_b.ensureCapacity(54);

        // Display Current Capacity st_b i.e.54
        System.out.println("st_b.ensureCapacity(54) = " + st_b.capacity());
    }
}

Output

输出量

st_b = Java World
st_b.capacity() = 26
st_b.ensureCapacity(54) = 54


翻译自: https://www.includehelp.com/java/stringbuilder-ensurecapacity-method-with-example.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值